* re-implement r41983 (forgot to add log message). Changes made:
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * @defgroup Parser Parser
4 *
5 * @file
6 * @ingroup Parser
7 * File for Parser and related classes
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are five main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * preprocess()
24 * removes HTML comments and expands templates
25 * cleanSig()
26 * Cleans a signature before saving it to preferences
27 * extractSections()
28 * Extracts sections from an article for section editing
29 *
30 * Globals used:
31 * objects: $wgLang, $wgContLang
32 *
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
34 *
35 * settings:
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
39 * $wgMaxArticleSize*
40 *
41 * * only within ParserOptions
42 * </pre>
43 *
44 * @ingroup Parser
45 */
46 class Parser
47 {
48 /**
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
52 */
53 const VERSION = '1.6.4';
54
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH = 1;
58 const SFH_OBJECT_ARGS = 2;
59
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
65
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT = 0;
68 const COLON_STATE_TAG = 1;
69 const COLON_STATE_TAGSTART = 2;
70 const COLON_STATE_CLOSETAG = 3;
71 const COLON_STATE_TAGSLASH = 4;
72 const COLON_STATE_COMMENT = 5;
73 const COLON_STATE_COMMENTDASH = 6;
74 const COLON_STATE_COMMENTDASHDASH = 7;
75
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION = 1;
78
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
81 const OT_HTML = 1;
82 const OT_WIKI = 2;
83 const OT_PREPROCESS = 3;
84 const OT_MSG = 3;
85
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX = "-QINU\x7f";
88
89 /**#@+
90 * @private
91 */
92 # Persistent:
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
96
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
106 var $mFileCache;
107
108 # Temporary
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
117
118 /**#@-*/
119
120 /**
121 * Constructor
122 *
123 * @public
124 */
125 function __construct( $conf = array() ) {
126 $this->mConf = $conf;
127 $this->mTagHooks = array();
128 $this->mTransparentTagHooks = array();
129 $this->mFunctionHooks = array();
130 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
131 $this->mDefaultStripList = $this->mStripList = array( 'nowiki', 'gallery', 'poem' );
132 $this->mUrlProtocols = wfUrlProtocols();
133 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
134 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
135 $this->mVarCache = array();
136 if ( isset( $conf['preprocessorClass'] ) ) {
137 $this->mPreprocessorClass = $conf['preprocessorClass'];
138 } elseif ( extension_loaded( 'domxml' ) ) {
139 // PECL extension that conflicts with the core DOM extension (bug 13770)
140 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
141 $this->mPreprocessorClass = 'Preprocessor_Hash';
142 } elseif ( extension_loaded( 'dom' ) ) {
143 $this->mPreprocessorClass = 'Preprocessor_DOM';
144 } else {
145 $this->mPreprocessorClass = 'Preprocessor_Hash';
146 }
147 $this->mMarkerIndex = 0;
148 $this->mFirstCall = true;
149 }
150
151 /**
152 * Reduce memory usage to reduce the impact of circular references
153 */
154 function __destruct() {
155 if ( isset( $this->mLinkHolders ) ) {
156 $this->mLinkHolders->__destruct();
157 }
158 foreach ( $this as $name => $value ) {
159 unset( $this->$name );
160 }
161 }
162
163 /**
164 * Do various kinds of initialisation on the first call of the parser
165 */
166 function firstCallInit() {
167 if ( !$this->mFirstCall ) {
168 return;
169 }
170 $this->mFirstCall = false;
171
172 wfProfileIn( __METHOD__ );
173
174 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
175 CoreParserFunctions::register( $this );
176 $this->initialiseVariables();
177
178 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
179 wfProfileOut( __METHOD__ );
180 }
181
182 /**
183 * Clear Parser state
184 *
185 * @private
186 */
187 function clearState() {
188 wfProfileIn( __METHOD__ );
189 if ( $this->mFirstCall ) {
190 $this->firstCallInit();
191 }
192 $this->mOutput = new ParserOutput;
193 $this->mAutonumber = 0;
194 $this->mLastSection = '';
195 $this->mDTopen = false;
196 $this->mIncludeCount = array();
197 $this->mStripState = new StripState;
198 $this->mArgStack = false;
199 $this->mInPre = false;
200 $this->mLinkHolders = new LinkHolderArray( $this );
201 $this->mLinkID = 0;
202 $this->mRevisionTimestamp = $this->mRevisionId = null;
203
204 /**
205 * Prefix for temporary replacement strings for the multipass parser.
206 * \x07 should never appear in input as it's disallowed in XML.
207 * Using it at the front also gives us a little extra robustness
208 * since it shouldn't match when butted up against identifier-like
209 * string constructs.
210 *
211 * Must not consist of all title characters, or else it will change
212 * the behaviour of <nowiki> in a link.
213 */
214 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
215 # Changed to \x7f to allow XML double-parsing -- TS
216 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
217
218
219 # Clear these on every parse, bug 4549
220 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
221
222 $this->mShowToc = true;
223 $this->mForceTocPosition = false;
224 $this->mIncludeSizes = array(
225 'post-expand' => 0,
226 'arg' => 0,
227 );
228 $this->mPPNodeCount = 0;
229 $this->mDefaultSort = false;
230 $this->mHeadings = array();
231 $this->mDoubleUnderscores = array();
232 $this->mExpensiveFunctionCount = 0;
233 $this->mFileCache = array();
234
235 # Fix cloning
236 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
237 $this->mPreprocessor = null;
238 }
239
240 wfRunHooks( 'ParserClearState', array( &$this ) );
241 wfProfileOut( __METHOD__ );
242 }
243
244 function setOutputType( $ot ) {
245 $this->mOutputType = $ot;
246 // Shortcut alias
247 $this->ot = array(
248 'html' => $ot == self::OT_HTML,
249 'wiki' => $ot == self::OT_WIKI,
250 'pre' => $ot == self::OT_PREPROCESS,
251 );
252 }
253
254 /**
255 * Set the context title
256 */
257 function setTitle( $t ) {
258 if ( !$t || $t instanceof FakeTitle ) {
259 $t = Title::newFromText( 'NO TITLE' );
260 }
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle = clone $t;
264 $this->mTitle->setFragment( '' );
265 } else {
266 $this->mTitle = $t;
267 }
268 }
269
270 /**
271 * Accessor for mUniqPrefix.
272 *
273 * @public
274 */
275 function uniqPrefix() {
276 if( !isset( $this->mUniqPrefix ) ) {
277 // @fixme this is probably *horribly wrong*
278 // LanguageConverter seems to want $wgParser's uniqPrefix, however
279 // if this is called for a parser cache hit, the parser may not
280 // have ever been initialized in the first place.
281 // Not really sure what the heck is supposed to be going on here.
282 return '';
283 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
284 }
285 return $this->mUniqPrefix;
286 }
287
288 /**
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
291 *
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
299 */
300 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
301 /**
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
304 */
305
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
307 $fname = __METHOD__.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__ );
309 wfProfileIn( $fname );
310
311 if ( $clearState ) {
312 $this->clearState();
313 }
314
315 $this->mOptions = $options;
316 $this->setTitle( $title );
317 $oldRevisionId = $this->mRevisionId;
318 $oldRevisionTimestamp = $this->mRevisionTimestamp;
319 if( $revid !== null ) {
320 $this->mRevisionId = $revid;
321 $this->mRevisionTimestamp = null;
322 }
323 $this->setOutputType( self::OT_HTML );
324 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
325 # No more strip!
326 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
327 $text = $this->internalParse( $text );
328 $text = $this->mStripState->unstripGeneral( $text );
329
330 # Clean up special characters, only run once, next-to-last before doBlockLevels
331 $fixtags = array(
332 # french spaces, last one Guillemet-left
333 # only if there is something before the space
334 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
335 # french spaces, Guillemet-right
336 '/(\\302\\253) /' => '\\1&nbsp;',
337 '/&nbsp;(!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
338 );
339 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
340
341 $text = $this->doBlockLevels( $text, $linestart );
342
343 $this->replaceLinkHolders( $text );
344
345 # the position of the parserConvert() call should not be changed. it
346 # assumes that the links are all replaced and the only thing left
347 # is the <nowiki> mark.
348 # Side-effects: this calls $this->mOutput->setTitleText()
349 $text = $wgContLang->parserConvert( $text, $this );
350
351 $text = $this->mStripState->unstripNoWiki( $text );
352
353 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
354
355 //!JF Move to its own function
356
357 $uniq_prefix = $this->mUniqPrefix;
358 $matches = array();
359 $elements = array_keys( $this->mTransparentTagHooks );
360 $text = self::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
361
362 foreach( $matches as $marker => $data ) {
363 list( $element, $content, $params, $tag ) = $data;
364 $tagName = strtolower( $element );
365 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
366 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
367 array( $content, $params, $this ) );
368 } else {
369 $output = $tag;
370 }
371 $this->mStripState->general->setPair( $marker, $output );
372 }
373 $text = $this->mStripState->unstripGeneral( $text );
374
375 $text = Sanitizer::normalizeCharReferences( $text );
376
377 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
378 $text = self::tidy($text);
379 } else {
380 # attempt to sanitize at least some nesting problems
381 # (bug #2702 and quite a few others)
382 $tidyregs = array(
383 # ''Something [http://www.cool.com cool''] -->
384 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
385 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
386 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
387 # fix up an anchor inside another anchor, only
388 # at least for a single single nested link (bug 3695)
389 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
390 '\\1\\2</a>\\3</a>\\1\\4</a>',
391 # fix div inside inline elements- doBlockLevels won't wrap a line which
392 # contains a div, so fix it up here; replace
393 # div with escaped text
394 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
395 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
396 # remove empty italic or bold tag pairs, some
397 # introduced by rules above
398 '/<([bi])><\/\\1>/' => '',
399 );
400
401 $text = preg_replace(
402 array_keys( $tidyregs ),
403 array_values( $tidyregs ),
404 $text );
405 }
406 global $wgExpensiveParserFunctionLimit;
407 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) {
408 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit );
409 }
410
411 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
412
413 # Information on include size limits, for the benefit of users who try to skirt them
414 if ( $this->mOptions->getEnableLimitReport() ) {
415 global $wgExpensiveParserFunctionLimit;
416 $max = $this->mOptions->getMaxIncludeSize();
417 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
418 $limitReport =
419 "NewPP limit report\n" .
420 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
421 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
422 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
423 $PFreport;
424 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
425 $text .= "\n<!-- \n$limitReport-->\n";
426 }
427 $this->mOutput->setText( $text );
428 $this->mRevisionId = $oldRevisionId;
429 $this->mRevisionTimestamp = $oldRevisionTimestamp;
430 wfProfileOut( $fname );
431 wfProfileOut( __METHOD__ );
432
433 return $this->mOutput;
434 }
435
436 /**
437 * Recursive parser entry point that can be called from an extension tag
438 * hook.
439 */
440 function recursiveTagParse( $text ) {
441 wfProfileIn( __METHOD__ );
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
444 $text = $this->internalParse( $text );
445 wfProfileOut( __METHOD__ );
446 return $text;
447 }
448
449 /**
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
452 */
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__ );
455 $this->clearState();
456 $this->setOutputType( self::OT_PREPROCESS );
457 $this->mOptions = $options;
458 $this->setTitle( $title );
459 if( $revid !== null ) {
460 $this->mRevisionId = $revid;
461 }
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState->unstripBoth( $text );
466 wfProfileOut( __METHOD__ );
467 return $text;
468 }
469
470 /**
471 * Get a random string
472 *
473 * @private
474 * @static
475 */
476 function getRandomString() {
477 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
478 }
479
480 function &getTitle() { return $this->mTitle; }
481 function getOptions() { return $this->mOptions; }
482 function getRevisionId() { return $this->mRevisionId; }
483 function getOutput() { return $this->mOutput; }
484 function nextLinkID() { return $this->mLinkID++; }
485
486 function getFunctionLang() {
487 global $wgLang, $wgContLang;
488
489 $target = $this->mOptions->getTargetLanguage();
490 if ( $target !== null ) {
491 return $target;
492 } else {
493 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
494 }
495 }
496
497 /**
498 * Get a preprocessor object
499 */
500 function getPreprocessor() {
501 if ( !isset( $this->mPreprocessor ) ) {
502 $class = $this->mPreprocessorClass;
503 $this->mPreprocessor = new $class( $this );
504 }
505 return $this->mPreprocessor;
506 }
507
508 /**
509 * Replaces all occurrences of HTML-style comments and the given tags
510 * in the text with a random marker and returns the next text. The output
511 * parameter $matches will be an associative array filled with data in
512 * the form:
513 * 'UNIQ-xxxxx' => array(
514 * 'element',
515 * 'tag content',
516 * array( 'param' => 'x' ),
517 * '<element param="x">tag content</element>' ) )
518 *
519 * @param $elements list of element names. Comments are always extracted.
520 * @param $text Source text string.
521 * @param $uniq_prefix
522 *
523 * @public
524 * @static
525 */
526 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
527 static $n = 1;
528 $stripped = '';
529 $matches = array();
530
531 $taglist = implode( '|', $elements );
532 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
533
534 while ( '' != $text ) {
535 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
536 $stripped .= $p[0];
537 if( count( $p ) < 5 ) {
538 break;
539 }
540 if( count( $p ) > 5 ) {
541 // comment
542 $element = $p[4];
543 $attributes = '';
544 $close = '';
545 $inside = $p[5];
546 } else {
547 // tag
548 $element = $p[1];
549 $attributes = $p[2];
550 $close = $p[3];
551 $inside = $p[4];
552 }
553
554 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . self::MARKER_SUFFIX;
555 $stripped .= $marker;
556
557 if ( $close === '/>' ) {
558 // Empty element tag, <tag />
559 $content = null;
560 $text = $inside;
561 $tail = null;
562 } else {
563 if( $element === '!--' ) {
564 $end = '/(-->)/';
565 } else {
566 $end = "/(<\\/$element\\s*>)/i";
567 }
568 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
569 $content = $q[0];
570 if( count( $q ) < 3 ) {
571 # No end tag -- let it run out to the end of the text.
572 $tail = '';
573 $text = '';
574 } else {
575 $tail = $q[1];
576 $text = $q[2];
577 }
578 }
579
580 $matches[$marker] = array( $element,
581 $content,
582 Sanitizer::decodeTagAttributes( $attributes ),
583 "<$element$attributes$close$content$tail" );
584 }
585 return $stripped;
586 }
587
588 /**
589 * Get a list of strippable XML-like elements
590 */
591 function getStripList() {
592 global $wgRawHtml;
593 $elements = $this->mStripList;
594 if( $wgRawHtml ) {
595 $elements[] = 'html';
596 }
597 if( $this->mOptions->getUseTeX() ) {
598 $elements[] = 'math';
599 }
600 return $elements;
601 }
602
603 /**
604 * @deprecated use replaceVariables
605 */
606 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
607 return $text;
608 }
609
610 /**
611 * Restores pre, math, and other extensions removed by strip()
612 *
613 * always call unstripNoWiki() after this one
614 * @private
615 * @deprecated use $this->mStripState->unstrip()
616 */
617 function unstrip( $text, $state ) {
618 return $state->unstripGeneral( $text );
619 }
620
621 /**
622 * Always call this after unstrip() to preserve the order
623 *
624 * @private
625 * @deprecated use $this->mStripState->unstrip()
626 */
627 function unstripNoWiki( $text, $state ) {
628 return $state->unstripNoWiki( $text );
629 }
630
631 /**
632 * @deprecated use $this->mStripState->unstripBoth()
633 */
634 function unstripForHTML( $text ) {
635 return $this->mStripState->unstripBoth( $text );
636 }
637
638 /**
639 * Add an item to the strip state
640 * Returns the unique tag which must be inserted into the stripped text
641 * The tag will be replaced with the original text in unstrip()
642 *
643 * @private
644 */
645 function insertStripItem( $text ) {
646 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
647 $this->mMarkerIndex++;
648 $this->mStripState->general->setPair( $rnd, $text );
649 return $rnd;
650 }
651
652 /**
653 * Interface with html tidy, used if $wgUseTidy = true.
654 * If tidy isn't able to correct the markup, the original will be
655 * returned in all its glory with a warning comment appended.
656 *
657 * Either the external tidy program or the in-process tidy extension
658 * will be used depending on availability. Override the default
659 * $wgTidyInternal setting to disable the internal if it's not working.
660 *
661 * @param string $text Hideous HTML input
662 * @return string Corrected HTML output
663 * @public
664 * @static
665 */
666 function tidy( $text ) {
667 global $wgTidyInternal;
668 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
669 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
670 '<head><title>test</title></head><body>'.$text.'</body></html>';
671 if( $wgTidyInternal ) {
672 $correctedtext = self::internalTidy( $wrappedtext );
673 } else {
674 $correctedtext = self::externalTidy( $wrappedtext );
675 }
676 if( is_null( $correctedtext ) ) {
677 wfDebug( "Tidy error detected!\n" );
678 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
679 }
680 return $correctedtext;
681 }
682
683 /**
684 * Spawn an external HTML tidy process and get corrected markup back from it.
685 *
686 * @private
687 * @static
688 */
689 function externalTidy( $text ) {
690 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
691 wfProfileIn( __METHOD__ );
692
693 $cleansource = '';
694 $opts = ' -utf8';
695
696 $descriptorspec = array(
697 0 => array('pipe', 'r'),
698 1 => array('pipe', 'w'),
699 2 => array('file', wfGetNull(), 'a')
700 );
701 $pipes = array();
702 if( function_exists('proc_open') ) {
703 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
704 if (is_resource($process)) {
705 // Theoretically, this style of communication could cause a deadlock
706 // here. If the stdout buffer fills up, then writes to stdin could
707 // block. This doesn't appear to happen with tidy, because tidy only
708 // writes to stdout after it's finished reading from stdin. Search
709 // for tidyParseStdin and tidySaveStdout in console/tidy.c
710 fwrite($pipes[0], $text);
711 fclose($pipes[0]);
712 while (!feof($pipes[1])) {
713 $cleansource .= fgets($pipes[1], 1024);
714 }
715 fclose($pipes[1]);
716 proc_close($process);
717 }
718 }
719
720 wfProfileOut( __METHOD__ );
721
722 if( $cleansource == '' && $text != '') {
723 // Some kind of error happened, so we couldn't get the corrected text.
724 // Just give up; we'll use the source text and append a warning.
725 return null;
726 } else {
727 return $cleansource;
728 }
729 }
730
731 /**
732 * Use the HTML tidy PECL extension to use the tidy library in-process,
733 * saving the overhead of spawning a new process.
734 *
735 * 'pear install tidy' should be able to compile the extension module.
736 *
737 * @private
738 * @static
739 */
740 function internalTidy( $text ) {
741 global $wgTidyConf, $IP, $wgDebugTidy;
742 wfProfileIn( __METHOD__ );
743
744 $tidy = new tidy;
745 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
746 $tidy->cleanRepair();
747 if( $tidy->getStatus() == 2 ) {
748 // 2 is magic number for fatal error
749 // http://www.php.net/manual/en/function.tidy-get-status.php
750 $cleansource = null;
751 } else {
752 $cleansource = tidy_get_output( $tidy );
753 }
754 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
755 $cleansource .= "<!--\nTidy reports:\n" .
756 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
757 "\n-->";
758 }
759
760 wfProfileOut( __METHOD__ );
761 return $cleansource;
762 }
763
764 /**
765 * parse the wiki syntax used to render tables
766 *
767 * @private
768 */
769 function doTableStuff ( $text ) {
770 wfProfileIn( __METHOD__ );
771
772 $lines = StringUtils::explode( "\n", $text );
773 $out = '';
774 $td_history = array (); // Is currently a td tag open?
775 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
776 $tr_history = array (); // Is currently a tr tag open?
777 $tr_attributes = array (); // history of tr attributes
778 $has_opened_tr = array(); // Did this table open a <tr> element?
779 $indent_level = 0; // indent level of the table
780
781 foreach ( $lines as $outLine ) {
782 $line = trim( $outLine );
783
784 if( $line == '' ) { // empty line, go to next line
785 $out .= $outLine."\n";
786 continue;
787 }
788 $first_character = $line[0];
789 $matches = array();
790
791 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
792 // First check if we are starting a new table
793 $indent_level = strlen( $matches[1] );
794
795 $attributes = $this->mStripState->unstripBoth( $matches[2] );
796 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
797
798 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
799 array_push ( $td_history , false );
800 array_push ( $last_tag_history , '' );
801 array_push ( $tr_history , false );
802 array_push ( $tr_attributes , '' );
803 array_push ( $has_opened_tr , false );
804 } else if ( count ( $td_history ) == 0 ) {
805 // Don't do any of the following
806 $out .= $outLine."\n";
807 continue;
808 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
809 // We are ending a table
810 $line = '</table>' . substr ( $line , 2 );
811 $last_tag = array_pop ( $last_tag_history );
812
813 if ( !array_pop ( $has_opened_tr ) ) {
814 $line = "<tr><td></td></tr>{$line}";
815 }
816
817 if ( array_pop ( $tr_history ) ) {
818 $line = "</tr>{$line}";
819 }
820
821 if ( array_pop ( $td_history ) ) {
822 $line = "</{$last_tag}>{$line}";
823 }
824 array_pop ( $tr_attributes );
825 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
826 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
827 // Now we have a table row
828 $line = preg_replace( '#^\|-+#', '', $line );
829
830 // Whats after the tag is now only attributes
831 $attributes = $this->mStripState->unstripBoth( $line );
832 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
833 array_pop ( $tr_attributes );
834 array_push ( $tr_attributes , $attributes );
835
836 $line = '';
837 $last_tag = array_pop ( $last_tag_history );
838 array_pop ( $has_opened_tr );
839 array_push ( $has_opened_tr , true );
840
841 if ( array_pop ( $tr_history ) ) {
842 $line = '</tr>';
843 }
844
845 if ( array_pop ( $td_history ) ) {
846 $line = "</{$last_tag}>{$line}";
847 }
848
849 $outLine = $line;
850 array_push ( $tr_history , false );
851 array_push ( $td_history , false );
852 array_push ( $last_tag_history , '' );
853 }
854 else if ( $first_character === '|' || $first_character === '!' || substr ( $line , 0 , 2 ) === '|+' ) {
855 // This might be cell elements, td, th or captions
856 if ( substr ( $line , 0 , 2 ) === '|+' ) {
857 $first_character = '+';
858 $line = substr ( $line , 1 );
859 }
860
861 $line = substr ( $line , 1 );
862
863 if ( $first_character === '!' ) {
864 $line = str_replace ( '!!' , '||' , $line );
865 }
866
867 // Split up multiple cells on the same line.
868 // FIXME : This can result in improper nesting of tags processed
869 // by earlier parser steps, but should avoid splitting up eg
870 // attribute values containing literal "||".
871 $cells = StringUtils::explodeMarkup( '||' , $line );
872
873 $outLine = '';
874
875 // Loop through each table cell
876 foreach ( $cells as $cell )
877 {
878 $previous = '';
879 if ( $first_character !== '+' )
880 {
881 $tr_after = array_pop ( $tr_attributes );
882 if ( !array_pop ( $tr_history ) ) {
883 $previous = "<tr{$tr_after}>\n";
884 }
885 array_push ( $tr_history , true );
886 array_push ( $tr_attributes , '' );
887 array_pop ( $has_opened_tr );
888 array_push ( $has_opened_tr , true );
889 }
890
891 $last_tag = array_pop ( $last_tag_history );
892
893 if ( array_pop ( $td_history ) ) {
894 $previous = "</{$last_tag}>{$previous}";
895 }
896
897 if ( $first_character === '|' ) {
898 $last_tag = 'td';
899 } else if ( $first_character === '!' ) {
900 $last_tag = 'th';
901 } else if ( $first_character === '+' ) {
902 $last_tag = 'caption';
903 } else {
904 $last_tag = '';
905 }
906
907 array_push ( $last_tag_history , $last_tag );
908
909 // A cell could contain both parameters and data
910 $cell_data = explode ( '|' , $cell , 2 );
911
912 // Bug 553: Note that a '|' inside an invalid link should not
913 // be mistaken as delimiting cell parameters
914 if ( strpos( $cell_data[0], '[[' ) !== false ) {
915 $cell = "{$previous}<{$last_tag}>{$cell}";
916 } else if ( count ( $cell_data ) == 1 )
917 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
918 else {
919 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
920 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
921 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
922 }
923
924 $outLine .= $cell;
925 array_push ( $td_history , true );
926 }
927 }
928 $out .= $outLine . "\n";
929 }
930
931 // Closing open td, tr && table
932 while ( count ( $td_history ) > 0 )
933 {
934 if ( array_pop ( $td_history ) ) {
935 $out .= "</td>\n";
936 }
937 if ( array_pop ( $tr_history ) ) {
938 $out .= "</tr>\n";
939 }
940 if ( !array_pop ( $has_opened_tr ) ) {
941 $out .= "<tr><td></td></tr>\n" ;
942 }
943
944 $out .= "</table>\n";
945 }
946
947 // Remove trailing line-ending (b/c)
948 if ( substr( $out, -1 ) === "\n" ) {
949 $out = substr( $out, 0, -1 );
950 }
951
952 // special case: don't return empty table
953 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
954 $out = '';
955 }
956
957 wfProfileOut( __METHOD__ );
958
959 return $out;
960 }
961
962 /**
963 * Helper function for parse() that transforms wiki markup into
964 * HTML. Only called for $mOutputType == self::OT_HTML.
965 *
966 * @private
967 */
968 function internalParse( $text ) {
969 $isMain = true;
970 wfProfileIn( __METHOD__ );
971
972 # Hook to suspend the parser in this state
973 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
974 wfProfileOut( __METHOD__ );
975 return $text ;
976 }
977
978 $text = $this->replaceVariables( $text );
979 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
980 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
981
982 // Tables need to come after variable replacement for things to work
983 // properly; putting them before other transformations should keep
984 // exciting things like link expansions from showing up in surprising
985 // places.
986 $text = $this->doTableStuff( $text );
987
988 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
989
990 $text = $this->doDoubleUnderscore( $text );
991 $text = $this->doHeadings( $text );
992 if($this->mOptions->getUseDynamicDates()) {
993 $df = DateFormatter::getInstance();
994 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
995 }
996 $text = $this->doAllQuotes( $text );
997 $text = $this->replaceInternalLinks( $text );
998 $text = $this->replaceExternalLinks( $text );
999
1000 # replaceInternalLinks may sometimes leave behind
1001 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1002 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
1003
1004 $text = $this->doMagicLinks( $text );
1005 $text = $this->formatHeadings( $text, $isMain );
1006
1007 wfProfileOut( __METHOD__ );
1008 return $text;
1009 }
1010
1011 /**
1012 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1013 * magic external links.
1014 *
1015 * DML
1016 * @private
1017 */
1018 function doMagicLinks( $text ) {
1019 wfProfileIn( __METHOD__ );
1020 $prots = $this->mUrlProtocols;
1021 $urlChar = self::EXT_LINK_URL_CLASS;
1022 $text = preg_replace_callback(
1023 '!(?: # Start cases
1024 (<a.*?</a>) | # m[1]: Skip link text
1025 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1026 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1027 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1028 ISBN\s+(\b # m[5]: ISBN, capture number
1029 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1030 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1031 [0-9Xx] # check digit
1032 \b)
1033 )!x', array( &$this, 'magicLinkCallback' ), $text );
1034 wfProfileOut( __METHOD__ );
1035 return $text;
1036 }
1037
1038 function magicLinkCallback( $m ) {
1039 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1040 # Skip anchor
1041 return $m[0];
1042 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1043 # Skip HTML element
1044 return $m[0];
1045 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1046 # Free external link
1047 return $this->makeFreeExternalLink( $m[0] );
1048 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1049 # RFC or PMID
1050 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1051 $keyword = 'RFC';
1052 $urlmsg = 'rfcurl';
1053 $id = $m[4];
1054 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1055 $keyword = 'PMID';
1056 $urlmsg = 'pubmedurl';
1057 $id = $m[4];
1058 } else {
1059 throw new MWException( __METHOD__.': unrecognised match type "' .
1060 substr($m[0], 0, 20 ) . '"' );
1061 }
1062 $url = wfMsg( $urlmsg, $id);
1063 $sk = $this->mOptions->getSkin();
1064 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1065 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1066 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1067 # ISBN
1068 $isbn = $m[5];
1069 $num = strtr( $isbn, array(
1070 '-' => '',
1071 ' ' => '',
1072 'x' => 'X',
1073 ));
1074 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1075 return'<a href="' .
1076 $titleObj->escapeLocalUrl() .
1077 "\" class=\"internal\">ISBN $isbn</a>";
1078 } else {
1079 return $m[0];
1080 }
1081 }
1082
1083 /**
1084 * Make a free external link, given a user-supplied URL
1085 * @return HTML
1086 * @private
1087 */
1088 function makeFreeExternalLink( $url ) {
1089 global $wgContLang;
1090 wfProfileIn( __METHOD__ );
1091
1092 $sk = $this->mOptions->getSkin();
1093 $trail = '';
1094
1095 # The characters '<' and '>' (which were escaped by
1096 # removeHTMLtags()) should not be included in
1097 # URLs, per RFC 2396.
1098 $m2 = array();
1099 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1100 $trail = substr($url, $m2[0][1]) . $trail;
1101 $url = substr($url, 0, $m2[0][1]);
1102 }
1103
1104 # Move trailing punctuation to $trail
1105 $sep = ',;\.:!?';
1106 # If there is no left bracket, then consider right brackets fair game too
1107 if ( strpos( $url, '(' ) === false ) {
1108 $sep .= ')';
1109 }
1110
1111 $numSepChars = strspn( strrev( $url ), $sep );
1112 if ( $numSepChars ) {
1113 $trail = substr( $url, -$numSepChars ) . $trail;
1114 $url = substr( $url, 0, -$numSepChars );
1115 }
1116
1117 $url = Sanitizer::cleanUrl( $url );
1118
1119 # Is this an external image?
1120 $text = $this->maybeMakeExternalImage( $url );
1121 if ( $text === false ) {
1122 # Not an image, make a link
1123 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1124 $this->getExternalLinkAttribs() );
1125 # Register it in the output object...
1126 # Replace unnecessary URL escape codes with their equivalent characters
1127 $pasteurized = self::replaceUnusualEscapes( $url );
1128 $this->mOutput->addExternalLink( $pasteurized );
1129 }
1130 wfProfileOut( __METHOD__ );
1131 return $text . $trail;
1132 }
1133
1134
1135 /**
1136 * Parse headers and return html
1137 *
1138 * @private
1139 */
1140 function doHeadings( $text ) {
1141 wfProfileIn( __METHOD__ );
1142 for ( $i = 6; $i >= 1; --$i ) {
1143 $h = str_repeat( '=', $i );
1144 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1145 "<h$i>\\1</h$i>", $text );
1146 }
1147 wfProfileOut( __METHOD__ );
1148 return $text;
1149 }
1150
1151 /**
1152 * Replace single quotes with HTML markup
1153 * @private
1154 * @return string the altered text
1155 */
1156 function doAllQuotes( $text ) {
1157 wfProfileIn( __METHOD__ );
1158 $outtext = '';
1159 $lines = StringUtils::explode( "\n", $text );
1160 foreach ( $lines as $line ) {
1161 $outtext .= $this->doQuotes( $line ) . "\n";
1162 }
1163 $outtext = substr($outtext, 0,-1);
1164 wfProfileOut( __METHOD__ );
1165 return $outtext;
1166 }
1167
1168 /**
1169 * Helper function for doAllQuotes()
1170 */
1171 public function doQuotes( $text ) {
1172 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1173 if ( count( $arr ) == 1 )
1174 return $text;
1175 else
1176 {
1177 # First, do some preliminary work. This may shift some apostrophes from
1178 # being mark-up to being text. It also counts the number of occurrences
1179 # of bold and italics mark-ups.
1180 $i = 0;
1181 $numbold = 0;
1182 $numitalics = 0;
1183 foreach ( $arr as $r )
1184 {
1185 if ( ( $i % 2 ) == 1 )
1186 {
1187 # If there are ever four apostrophes, assume the first is supposed to
1188 # be text, and the remaining three constitute mark-up for bold text.
1189 if ( strlen( $arr[$i] ) == 4 )
1190 {
1191 $arr[$i-1] .= "'";
1192 $arr[$i] = "'''";
1193 }
1194 # If there are more than 5 apostrophes in a row, assume they're all
1195 # text except for the last 5.
1196 else if ( strlen( $arr[$i] ) > 5 )
1197 {
1198 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1199 $arr[$i] = "'''''";
1200 }
1201 # Count the number of occurrences of bold and italics mark-ups.
1202 # We are not counting sequences of five apostrophes.
1203 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1204 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1205 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1206 }
1207 $i++;
1208 }
1209
1210 # If there is an odd number of both bold and italics, it is likely
1211 # that one of the bold ones was meant to be an apostrophe followed
1212 # by italics. Which one we cannot know for certain, but it is more
1213 # likely to be one that has a single-letter word before it.
1214 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1215 {
1216 $i = 0;
1217 $firstsingleletterword = -1;
1218 $firstmultiletterword = -1;
1219 $firstspace = -1;
1220 foreach ( $arr as $r )
1221 {
1222 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1223 {
1224 $x1 = substr ($arr[$i-1], -1);
1225 $x2 = substr ($arr[$i-1], -2, 1);
1226 if ($x1 === ' ') {
1227 if ($firstspace == -1) $firstspace = $i;
1228 } else if ($x2 === ' ') {
1229 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1230 } else {
1231 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1232 }
1233 }
1234 $i++;
1235 }
1236
1237 # If there is a single-letter word, use it!
1238 if ($firstsingleletterword > -1)
1239 {
1240 $arr [ $firstsingleletterword ] = "''";
1241 $arr [ $firstsingleletterword-1 ] .= "'";
1242 }
1243 # If not, but there's a multi-letter word, use that one.
1244 else if ($firstmultiletterword > -1)
1245 {
1246 $arr [ $firstmultiletterword ] = "''";
1247 $arr [ $firstmultiletterword-1 ] .= "'";
1248 }
1249 # ... otherwise use the first one that has neither.
1250 # (notice that it is possible for all three to be -1 if, for example,
1251 # there is only one pentuple-apostrophe in the line)
1252 else if ($firstspace > -1)
1253 {
1254 $arr [ $firstspace ] = "''";
1255 $arr [ $firstspace-1 ] .= "'";
1256 }
1257 }
1258
1259 # Now let's actually convert our apostrophic mush to HTML!
1260 $output = '';
1261 $buffer = '';
1262 $state = '';
1263 $i = 0;
1264 foreach ($arr as $r)
1265 {
1266 if (($i % 2) == 0)
1267 {
1268 if ($state === 'both')
1269 $buffer .= $r;
1270 else
1271 $output .= $r;
1272 }
1273 else
1274 {
1275 if (strlen ($r) == 2)
1276 {
1277 if ($state === 'i')
1278 { $output .= '</i>'; $state = ''; }
1279 else if ($state === 'bi')
1280 { $output .= '</i>'; $state = 'b'; }
1281 else if ($state === 'ib')
1282 { $output .= '</b></i><b>'; $state = 'b'; }
1283 else if ($state === 'both')
1284 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1285 else # $state can be 'b' or ''
1286 { $output .= '<i>'; $state .= 'i'; }
1287 }
1288 else if (strlen ($r) == 3)
1289 {
1290 if ($state === 'b')
1291 { $output .= '</b>'; $state = ''; }
1292 else if ($state === 'bi')
1293 { $output .= '</i></b><i>'; $state = 'i'; }
1294 else if ($state === 'ib')
1295 { $output .= '</b>'; $state = 'i'; }
1296 else if ($state === 'both')
1297 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1298 else # $state can be 'i' or ''
1299 { $output .= '<b>'; $state .= 'b'; }
1300 }
1301 else if (strlen ($r) == 5)
1302 {
1303 if ($state === 'b')
1304 { $output .= '</b><i>'; $state = 'i'; }
1305 else if ($state === 'i')
1306 { $output .= '</i><b>'; $state = 'b'; }
1307 else if ($state === 'bi')
1308 { $output .= '</i></b>'; $state = ''; }
1309 else if ($state === 'ib')
1310 { $output .= '</b></i>'; $state = ''; }
1311 else if ($state === 'both')
1312 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1313 else # ($state == '')
1314 { $buffer = ''; $state = 'both'; }
1315 }
1316 }
1317 $i++;
1318 }
1319 # Now close all remaining tags. Notice that the order is important.
1320 if ($state === 'b' || $state === 'ib')
1321 $output .= '</b>';
1322 if ($state === 'i' || $state === 'bi' || $state === 'ib')
1323 $output .= '</i>';
1324 if ($state === 'bi')
1325 $output .= '</b>';
1326 # There might be lonely ''''', so make sure we have a buffer
1327 if ($state === 'both' && $buffer)
1328 $output .= '<b><i>'.$buffer.'</i></b>';
1329 return $output;
1330 }
1331 }
1332
1333 /**
1334 * Replace external links (REL)
1335 *
1336 * Note: this is all very hackish and the order of execution matters a lot.
1337 * Make sure to run maintenance/parserTests.php if you change this code.
1338 *
1339 * @private
1340 */
1341 function replaceExternalLinks( $text ) {
1342 global $wgContLang;
1343 wfProfileIn( __METHOD__ );
1344
1345 $sk = $this->mOptions->getSkin();
1346
1347 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1348 $s = array_shift( $bits );
1349
1350 $i = 0;
1351 while ( $i<count( $bits ) ) {
1352 $url = $bits[$i++];
1353 $protocol = $bits[$i++];
1354 $text = $bits[$i++];
1355 $trail = $bits[$i++];
1356
1357 # The characters '<' and '>' (which were escaped by
1358 # removeHTMLtags()) should not be included in
1359 # URLs, per RFC 2396.
1360 $m2 = array();
1361 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1362 $text = substr($url, $m2[0][1]) . ' ' . $text;
1363 $url = substr($url, 0, $m2[0][1]);
1364 }
1365
1366 # If the link text is an image URL, replace it with an <img> tag
1367 # This happened by accident in the original parser, but some people used it extensively
1368 $img = $this->maybeMakeExternalImage( $text );
1369 if ( $img !== false ) {
1370 $text = $img;
1371 }
1372
1373 $dtrail = '';
1374
1375 # Set linktype for CSS - if URL==text, link is essentially free
1376 $linktype = ($text === $url) ? 'free' : 'text';
1377
1378 # No link text, e.g. [http://domain.tld/some.link]
1379 if ( $text == '' ) {
1380 # Autonumber if allowed. See bug #5918
1381 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1382 $langObj = $this->getFunctionLang();
1383 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1384 $linktype = 'autonumber';
1385 } else {
1386 # Otherwise just use the URL
1387 $text = htmlspecialchars( $url );
1388 $linktype = 'free';
1389 }
1390 } else {
1391 # Have link text, e.g. [http://domain.tld/some.link text]s
1392 # Check for trail
1393 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1394 }
1395
1396 $text = $wgContLang->markNoConversion($text);
1397
1398 $url = Sanitizer::cleanUrl( $url );
1399
1400 if ( $this->mOptions->mExternalLinkTarget ) {
1401 $attribs = array( 'target' => $this->mOptions->mExternalLinkTarget );
1402 } else {
1403 $attribs = array();
1404 }
1405
1406 # Use the encoded URL
1407 # This means that users can paste URLs directly into the text
1408 # Funny characters like &ouml; aren't valid in URLs anyway
1409 # This was changed in August 2004
1410 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->getExternalLinkAttribs() )
1411 . $dtrail . $trail;
1412
1413 # Register link in the output object.
1414 # Replace unnecessary URL escape codes with the referenced character
1415 # This prevents spammers from hiding links from the filters
1416 $pasteurized = self::replaceUnusualEscapes( $url );
1417 $this->mOutput->addExternalLink( $pasteurized );
1418 }
1419
1420 wfProfileOut( __METHOD__ );
1421 return $s;
1422 }
1423
1424 function getExternalLinkAttribs() {
1425 $attribs = array();
1426 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1427 $ns = $this->mTitle->getNamespace();
1428 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1429 $attribs['rel'] = 'nofollow';
1430 }
1431 if ( $this->mOptions->getExternalLinkTarget() ) {
1432 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1433 }
1434 return $attribs;
1435 }
1436
1437
1438 /**
1439 * Replace unusual URL escape codes with their equivalent characters
1440 * @param string
1441 * @return string
1442 * @static
1443 * @todo This can merge genuinely required bits in the path or query string,
1444 * breaking legit URLs. A proper fix would treat the various parts of
1445 * the URL differently; as a workaround, just use the output for
1446 * statistical records, not for actual linking/output.
1447 */
1448 static function replaceUnusualEscapes( $url ) {
1449 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1450 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1451 }
1452
1453 /**
1454 * Callback function used in replaceUnusualEscapes().
1455 * Replaces unusual URL escape codes with their equivalent character
1456 * @static
1457 * @private
1458 */
1459 private static function replaceUnusualEscapesCallback( $matches ) {
1460 $char = urldecode( $matches[0] );
1461 $ord = ord( $char );
1462 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1463 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1464 // No, shouldn't be escaped
1465 return $char;
1466 } else {
1467 // Yes, leave it escaped
1468 return $matches[0];
1469 }
1470 }
1471
1472 /**
1473 * make an image if it's allowed, either through the global
1474 * option, through the exception, or through the on-wiki whitelist
1475 * @private
1476 */
1477 function maybeMakeExternalImage( $url ) {
1478 $sk = $this->mOptions->getSkin();
1479 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1480 $imagesexception = !empty($imagesfrom);
1481 $text = false;
1482 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1483 if( $imagesexception && is_array( $imagesfrom ) ) {
1484 $imagematch = false;
1485 foreach( $imagesfrom as $match ) {
1486 if( strpos( $url, $match ) === 0 ) {
1487 $imagematch = true;
1488 break;
1489 }
1490 }
1491 } elseif( $imagesexception ) {
1492 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1493 } else {
1494 $imagematch = false;
1495 }
1496 if ( $this->mOptions->getAllowExternalImages()
1497 || ( $imagesexception && $imagematch ) ) {
1498 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1499 # Image found
1500 $text = $sk->makeExternalImage( $url );
1501 }
1502 }
1503 if( !$text && $this->mOptions->getEnableImageWhitelist()
1504 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1505 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1506 foreach( $whitelist as $entry ) {
1507 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1508 if( strpos( $entry, '#' ) === 0 || $entry === '' )
1509 continue;
1510 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1511 # Image matches a whitelist entry
1512 $text = $sk->makeExternalImage( $url );
1513 break;
1514 }
1515 }
1516 }
1517 return $text;
1518 }
1519
1520 /**
1521 * Process [[ ]] wikilinks
1522 * @return processed text
1523 *
1524 * @private
1525 */
1526 function replaceInternalLinks( $s ) {
1527 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1528 return $s;
1529 }
1530
1531 /**
1532 * Process [[ ]] wikilinks (RIL)
1533 * @return LinkHolderArray
1534 *
1535 * @private
1536 */
1537 function replaceInternalLinks2( &$s ) {
1538 global $wgContLang;
1539
1540 wfProfileIn( __METHOD__ );
1541
1542 wfProfileIn( __METHOD__.'-setup' );
1543 static $tc = FALSE, $e1, $e1_img;
1544 # the % is needed to support urlencoded titles as well
1545 if ( !$tc ) {
1546 $tc = Title::legalChars() . '#%';
1547 # Match a link having the form [[namespace:link|alternate]]trail
1548 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1549 # Match cases where there is no "]]", which might still be images
1550 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1551 }
1552
1553 $sk = $this->mOptions->getSkin();
1554 $holders = new LinkHolderArray( $this );
1555
1556 #split the entire text string on occurences of [[
1557 $a = StringUtils::explode( '[[', ' ' . $s );
1558 #get the first element (all text up to first [[), and remove the space we added
1559 $s = $a->current();
1560 $a->next();
1561 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1562 $s = substr( $s, 1 );
1563
1564 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1565 $e2 = null;
1566 if ( $useLinkPrefixExtension ) {
1567 # Match the end of a line for a word that's not followed by whitespace,
1568 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1569 $e2 = wfMsgForContent( 'linkprefix' );
1570 }
1571
1572 if( is_null( $this->mTitle ) ) {
1573 wfProfileOut( __METHOD__.'-setup' );
1574 wfProfileOut( __METHOD__ );
1575 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1576 }
1577 $nottalk = !$this->mTitle->isTalkPage();
1578
1579 if ( $useLinkPrefixExtension ) {
1580 $m = array();
1581 if ( preg_match( $e2, $s, $m ) ) {
1582 $first_prefix = $m[2];
1583 } else {
1584 $first_prefix = false;
1585 }
1586 } else {
1587 $prefix = '';
1588 }
1589
1590 if($wgContLang->hasVariants()) {
1591 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1592 } else {
1593 $selflink = array($this->mTitle->getPrefixedText());
1594 }
1595 $useSubpages = $this->areSubpagesAllowed();
1596 wfProfileOut( __METHOD__.'-setup' );
1597
1598 # Loop for each link
1599 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1600 # Check for excessive memory usage
1601 if ( $holders->isBig() ) {
1602 # Too big
1603 # Do the existence check, replace the link holders and clear the array
1604 $holders->replace( $s );
1605 $holders->clear();
1606 }
1607
1608 if ( $useLinkPrefixExtension ) {
1609 wfProfileIn( __METHOD__.'-prefixhandling' );
1610 if ( preg_match( $e2, $s, $m ) ) {
1611 $prefix = $m[2];
1612 $s = $m[1];
1613 } else {
1614 $prefix='';
1615 }
1616 # first link
1617 if($first_prefix) {
1618 $prefix = $first_prefix;
1619 $first_prefix = false;
1620 }
1621 wfProfileOut( __METHOD__.'-prefixhandling' );
1622 }
1623
1624 $might_be_img = false;
1625
1626 wfProfileIn( __METHOD__."-e1" );
1627 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1628 $text = $m[2];
1629 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1630 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1631 # the real problem is with the $e1 regex
1632 # See bug 1300.
1633 #
1634 # Still some problems for cases where the ] is meant to be outside punctuation,
1635 # and no image is in sight. See bug 2095.
1636 #
1637 if( $text !== '' &&
1638 substr( $m[3], 0, 1 ) === ']' &&
1639 strpos($text, '[') !== false
1640 )
1641 {
1642 $text .= ']'; # so that replaceExternalLinks($text) works later
1643 $m[3] = substr( $m[3], 1 );
1644 }
1645 # fix up urlencoded title texts
1646 if( strpos( $m[1], '%' ) !== false ) {
1647 # Should anchors '#' also be rejected?
1648 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1649 }
1650 $trail = $m[3];
1651 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1652 $might_be_img = true;
1653 $text = $m[2];
1654 if ( strpos( $m[1], '%' ) !== false ) {
1655 $m[1] = urldecode($m[1]);
1656 }
1657 $trail = "";
1658 } else { # Invalid form; output directly
1659 $s .= $prefix . '[[' . $line ;
1660 wfProfileOut( __METHOD__."-e1" );
1661 continue;
1662 }
1663 wfProfileOut( __METHOD__."-e1" );
1664 wfProfileIn( __METHOD__."-misc" );
1665
1666 # Don't allow internal links to pages containing
1667 # PROTO: where PROTO is a valid URL protocol; these
1668 # should be external links.
1669 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1670 $s .= $prefix . '[[' . $line ;
1671 wfProfileOut( __METHOD__."-misc" );
1672 continue;
1673 }
1674
1675 # Make subpage if necessary
1676 if( $useSubpages ) {
1677 $link = $this->maybeDoSubpageLink( $m[1], $text );
1678 } else {
1679 $link = $m[1];
1680 }
1681
1682 $noforce = (substr($m[1], 0, 1) !== ':');
1683 if (!$noforce) {
1684 # Strip off leading ':'
1685 $link = substr($link, 1);
1686 }
1687
1688 wfProfileOut( __METHOD__."-misc" );
1689 wfProfileIn( __METHOD__."-title" );
1690 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1691 if( !$nt ) {
1692 $s .= $prefix . '[[' . $line;
1693 wfProfileOut( __METHOD__."-title" );
1694 continue;
1695 }
1696
1697 $ns = $nt->getNamespace();
1698 $iw = $nt->getInterWiki();
1699 wfProfileOut( __METHOD__."-title" );
1700
1701 if ($might_be_img) { # if this is actually an invalid link
1702 wfProfileIn( __METHOD__."-might_be_img" );
1703 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1704 $found = false;
1705 while ( true ) {
1706 #look at the next 'line' to see if we can close it there
1707 $a->next();
1708 $next_line = $a->current();
1709 if ( $next_line === false || $next_line === null ) {
1710 break;
1711 }
1712 $m = explode( ']]', $next_line, 3 );
1713 if ( count( $m ) == 3 ) {
1714 # the first ]] closes the inner link, the second the image
1715 $found = true;
1716 $text .= "[[{$m[0]}]]{$m[1]}";
1717 $trail = $m[2];
1718 break;
1719 } elseif ( count( $m ) == 2 ) {
1720 #if there's exactly one ]] that's fine, we'll keep looking
1721 $text .= "[[{$m[0]}]]{$m[1]}";
1722 } else {
1723 #if $next_line is invalid too, we need look no further
1724 $text .= '[[' . $next_line;
1725 break;
1726 }
1727 }
1728 if ( !$found ) {
1729 # we couldn't find the end of this imageLink, so output it raw
1730 #but don't ignore what might be perfectly normal links in the text we've examined
1731 $holders->merge( $this->replaceInternalLinks2( $text ) );
1732 $s .= "{$prefix}[[$link|$text";
1733 # note: no $trail, because without an end, there *is* no trail
1734 wfProfileOut( __METHOD__."-might_be_img" );
1735 continue;
1736 }
1737 } else { #it's not an image, so output it raw
1738 $s .= "{$prefix}[[$link|$text";
1739 # note: no $trail, because without an end, there *is* no trail
1740 wfProfileOut( __METHOD__."-might_be_img" );
1741 continue;
1742 }
1743 wfProfileOut( __METHOD__."-might_be_img" );
1744 }
1745
1746 $wasblank = ( '' == $text );
1747 if( $wasblank ) $text = $link;
1748
1749 # Link not escaped by : , create the various objects
1750 if( $noforce ) {
1751
1752 # Interwikis
1753 wfProfileIn( __METHOD__."-interwiki" );
1754 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1755 $this->mOutput->addLanguageLink( $nt->getFullText() );
1756 $s = rtrim($s . $prefix);
1757 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1758 wfProfileOut( __METHOD__."-interwiki" );
1759 continue;
1760 }
1761 wfProfileOut( __METHOD__."-interwiki" );
1762
1763 if ( $ns == NS_IMAGE ) {
1764 wfProfileIn( __METHOD__."-image" );
1765 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1766 # recursively parse links inside the image caption
1767 # actually, this will parse them in any other parameters, too,
1768 # but it might be hard to fix that, and it doesn't matter ATM
1769 $text = $this->replaceExternalLinks($text);
1770 $holders->merge( $this->replaceInternalLinks2( $text ) );
1771
1772 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1773 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1774 }
1775 $this->mOutput->addImage( $nt->getDBkey() );
1776 wfProfileOut( __METHOD__."-image" );
1777 continue;
1778
1779 }
1780
1781 if ( $ns == NS_CATEGORY ) {
1782 wfProfileIn( __METHOD__."-category" );
1783 $s = rtrim($s . "\n"); # bug 87
1784
1785 if ( $wasblank ) {
1786 $sortkey = $this->getDefaultSort();
1787 } else {
1788 $sortkey = $text;
1789 }
1790 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1791 $sortkey = str_replace( "\n", '', $sortkey );
1792 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1793 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1794
1795 /**
1796 * Strip the whitespace Category links produce, see bug 87
1797 * @todo We might want to use trim($tmp, "\n") here.
1798 */
1799 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1800
1801 wfProfileOut( __METHOD__."-category" );
1802 continue;
1803 }
1804 }
1805
1806 # Self-link checking
1807 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL ) {
1808 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1809 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1810 continue;
1811 }
1812 }
1813
1814 # Special and Media are pseudo-namespaces; no pages actually exist in them
1815 if( $ns == NS_MEDIA ) {
1816 # Give extensions a chance to select the file revision for us
1817 $skip = $time = false;
1818 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1819 if ( $skip ) {
1820 $link = $sk->link( $nt );
1821 } else {
1822 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1823 }
1824 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1825 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1826 $this->mOutput->addImage( $nt->getDBkey() );
1827 continue;
1828 } elseif( $ns == NS_SPECIAL ) {
1829 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1830 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1831 } else {
1832 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1833 }
1834 continue;
1835 } elseif( $ns == NS_IMAGE ) {
1836 $img = wfFindFile( $nt );
1837 if( $img ) {
1838 // Force a blue link if the file exists; may be a remote
1839 // upload on the shared repository, and we want to see its
1840 // auto-generated page.
1841 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1842 $this->mOutput->addLink( $nt );
1843 continue;
1844 }
1845 }
1846 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1847 }
1848 wfProfileOut( __METHOD__ );
1849 return $holders;
1850 }
1851
1852 /**
1853 * Make a link placeholder. The text returned can be later resolved to a real link with
1854 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1855 * parsing of interwiki links, and secondly to allow all existence checks and
1856 * article length checks (for stub links) to be bundled into a single query.
1857 *
1858 * @deprecated
1859 */
1860 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1861 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1862 }
1863
1864 /**
1865 * Render a forced-blue link inline; protect against double expansion of
1866 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1867 * Since this little disaster has to split off the trail text to avoid
1868 * breaking URLs in the following text without breaking trails on the
1869 * wiki links, it's been made into a horrible function.
1870 *
1871 * @param Title $nt
1872 * @param string $text
1873 * @param string $query
1874 * @param string $trail
1875 * @param string $prefix
1876 * @return string HTML-wikitext mix oh yuck
1877 */
1878 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1879 list( $inside, $trail ) = Linker::splitTrail( $trail );
1880 $sk = $this->mOptions->getSkin();
1881 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1882 return $this->armorLinks( $link ) . $trail;
1883 }
1884
1885 /**
1886 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1887 * going to go through further parsing steps before inline URL expansion.
1888 *
1889 * Not needed quite as much as it used to be since free links are a bit
1890 * more sensible these days. But bracketed links are still an issue.
1891 *
1892 * @param string more-or-less HTML
1893 * @return string less-or-more HTML with NOPARSE bits
1894 */
1895 function armorLinks( $text ) {
1896 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1897 "{$this->mUniqPrefix}NOPARSE$1", $text );
1898 }
1899
1900 /**
1901 * Return true if subpage links should be expanded on this page.
1902 * @return bool
1903 */
1904 function areSubpagesAllowed() {
1905 # Some namespaces don't allow subpages
1906 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1907 }
1908
1909 /**
1910 * Handle link to subpage if necessary
1911 * @param string $target the source of the link
1912 * @param string &$text the link text, modified as necessary
1913 * @return string the full name of the link
1914 * @private
1915 */
1916 function maybeDoSubpageLink($target, &$text) {
1917 # Valid link forms:
1918 # Foobar -- normal
1919 # :Foobar -- override special treatment of prefix (images, language links)
1920 # /Foobar -- convert to CurrentPage/Foobar
1921 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1922 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1923 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1924
1925 wfProfileIn( __METHOD__ );
1926 $ret = $target; # default return value is no change
1927
1928 # Some namespaces don't allow subpages,
1929 # so only perform processing if subpages are allowed
1930 if( $this->areSubpagesAllowed() ) {
1931 $hash = strpos( $target, '#' );
1932 if( $hash !== false ) {
1933 $suffix = substr( $target, $hash );
1934 $target = substr( $target, 0, $hash );
1935 } else {
1936 $suffix = '';
1937 }
1938 # bug 7425
1939 $target = trim( $target );
1940 # Look at the first character
1941 if( $target != '' && $target{0} === '/' ) {
1942 # / at end means we don't want the slash to be shown
1943 $m = array();
1944 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1945 if( $trailingSlashes ) {
1946 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1947 } else {
1948 $noslash = substr( $target, 1 );
1949 }
1950
1951 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1952 if( '' === $text ) {
1953 $text = $target . $suffix;
1954 } # this might be changed for ugliness reasons
1955 } else {
1956 # check for .. subpage backlinks
1957 $dotdotcount = 0;
1958 $nodotdot = $target;
1959 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1960 ++$dotdotcount;
1961 $nodotdot = substr( $nodotdot, 3 );
1962 }
1963 if($dotdotcount > 0) {
1964 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1965 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1966 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1967 # / at the end means don't show full path
1968 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1969 $nodotdot = substr( $nodotdot, 0, -1 );
1970 if( '' === $text ) {
1971 $text = $nodotdot . $suffix;
1972 }
1973 }
1974 $nodotdot = trim( $nodotdot );
1975 if( $nodotdot != '' ) {
1976 $ret .= '/' . $nodotdot;
1977 }
1978 $ret .= $suffix;
1979 }
1980 }
1981 }
1982 }
1983
1984 wfProfileOut( __METHOD__ );
1985 return $ret;
1986 }
1987
1988 /**#@+
1989 * Used by doBlockLevels()
1990 * @private
1991 */
1992 /* private */ function closeParagraph() {
1993 $result = '';
1994 if ( '' != $this->mLastSection ) {
1995 $result = '</' . $this->mLastSection . ">\n";
1996 }
1997 $this->mInPre = false;
1998 $this->mLastSection = '';
1999 return $result;
2000 }
2001 # getCommon() returns the length of the longest common substring
2002 # of both arguments, starting at the beginning of both.
2003 #
2004 /* private */ function getCommon( $st1, $st2 ) {
2005 $fl = strlen( $st1 );
2006 $shorter = strlen( $st2 );
2007 if ( $fl < $shorter ) { $shorter = $fl; }
2008
2009 for ( $i = 0; $i < $shorter; ++$i ) {
2010 if ( $st1{$i} != $st2{$i} ) { break; }
2011 }
2012 return $i;
2013 }
2014 # These next three functions open, continue, and close the list
2015 # element appropriate to the prefix character passed into them.
2016 #
2017 /* private */ function openList( $char ) {
2018 $result = $this->closeParagraph();
2019
2020 if ( '*' === $char ) { $result .= '<ul><li>'; }
2021 else if ( '#' === $char ) { $result .= '<ol><li>'; }
2022 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
2023 else if ( ';' === $char ) {
2024 $result .= '<dl><dt>';
2025 $this->mDTopen = true;
2026 }
2027 else { $result = '<!-- ERR 1 -->'; }
2028
2029 return $result;
2030 }
2031
2032 /* private */ function nextItem( $char ) {
2033 if ( '*' === $char || '#' === $char ) { return '</li><li>'; }
2034 else if ( ':' === $char || ';' === $char ) {
2035 $close = '</dd>';
2036 if ( $this->mDTopen ) { $close = '</dt>'; }
2037 if ( ';' === $char ) {
2038 $this->mDTopen = true;
2039 return $close . '<dt>';
2040 } else {
2041 $this->mDTopen = false;
2042 return $close . '<dd>';
2043 }
2044 }
2045 return '<!-- ERR 2 -->';
2046 }
2047
2048 /* private */ function closeList( $char ) {
2049 if ( '*' === $char ) { $text = '</li></ul>'; }
2050 else if ( '#' === $char ) { $text = '</li></ol>'; }
2051 else if ( ':' === $char ) {
2052 if ( $this->mDTopen ) {
2053 $this->mDTopen = false;
2054 $text = '</dt></dl>';
2055 } else {
2056 $text = '</dd></dl>';
2057 }
2058 }
2059 else { return '<!-- ERR 3 -->'; }
2060 return $text."\n";
2061 }
2062 /**#@-*/
2063
2064 /**
2065 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2066 *
2067 * @private
2068 * @return string the lists rendered as HTML
2069 */
2070 function doBlockLevels( $text, $linestart ) {
2071 wfProfileIn( __METHOD__ );
2072
2073 # Parsing through the text line by line. The main thing
2074 # happening here is handling of block-level elements p, pre,
2075 # and making lists from lines starting with * # : etc.
2076 #
2077 $textLines = StringUtils::explode( "\n", $text );
2078
2079 $lastPrefix = $output = '';
2080 $this->mDTopen = $inBlockElem = false;
2081 $prefixLength = 0;
2082 $paragraphStack = false;
2083
2084 foreach ( $textLines as $oLine ) {
2085 # Fix up $linestart
2086 if ( !$linestart ) {
2087 $output .= $oLine;
2088 $linestart = true;
2089 continue;
2090 }
2091
2092 $lastPrefixLength = strlen( $lastPrefix );
2093 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2094 $preOpenMatch = preg_match('/<pre/i', $oLine );
2095 if ( !$this->mInPre ) {
2096 # Multiple prefixes may abut each other for nested lists.
2097 $prefixLength = strspn( $oLine, '*#:;' );
2098 $prefix = substr( $oLine, 0, $prefixLength );
2099
2100 # eh?
2101 $prefix2 = str_replace( ';', ':', $prefix );
2102 $t = substr( $oLine, $prefixLength );
2103 $this->mInPre = (bool)$preOpenMatch;
2104 } else {
2105 # Don't interpret any other prefixes in preformatted text
2106 $prefixLength = 0;
2107 $prefix = $prefix2 = '';
2108 $t = $oLine;
2109 }
2110
2111 # List generation
2112 if( $prefixLength && $lastPrefix === $prefix2 ) {
2113 # Same as the last item, so no need to deal with nesting or opening stuff
2114 $output .= $this->nextItem( substr( $prefix, -1 ) );
2115 $paragraphStack = false;
2116
2117 if ( substr( $prefix, -1 ) === ';') {
2118 # The one nasty exception: definition lists work like this:
2119 # ; title : definition text
2120 # So we check for : in the remainder text to split up the
2121 # title and definition, without b0rking links.
2122 $term = $t2 = '';
2123 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2124 $t = $t2;
2125 $output .= $term . $this->nextItem( ':' );
2126 }
2127 }
2128 } elseif( $prefixLength || $lastPrefixLength ) {
2129 # Either open or close a level...
2130 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2131 $paragraphStack = false;
2132
2133 while( $commonPrefixLength < $lastPrefixLength ) {
2134 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2135 --$lastPrefixLength;
2136 }
2137 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2138 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2139 }
2140 while ( $prefixLength > $commonPrefixLength ) {
2141 $char = substr( $prefix, $commonPrefixLength, 1 );
2142 $output .= $this->openList( $char );
2143
2144 if ( ';' === $char ) {
2145 # FIXME: This is dupe of code above
2146 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2147 $t = $t2;
2148 $output .= $term . $this->nextItem( ':' );
2149 }
2150 }
2151 ++$commonPrefixLength;
2152 }
2153 $lastPrefix = $prefix2;
2154 }
2155 if( 0 == $prefixLength ) {
2156 wfProfileIn( __METHOD__."-paragraph" );
2157 # No prefix (not in list)--go to paragraph mode
2158 // XXX: use a stack for nestable elements like span, table and div
2159 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2160 $closematch = preg_match(
2161 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2162 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2163 if ( $openmatch or $closematch ) {
2164 $paragraphStack = false;
2165 # TODO bug 5718: paragraph closed
2166 $output .= $this->closeParagraph();
2167 if ( $preOpenMatch and !$preCloseMatch ) {
2168 $this->mInPre = true;
2169 }
2170 if ( $closematch ) {
2171 $inBlockElem = false;
2172 } else {
2173 $inBlockElem = true;
2174 }
2175 } else if ( !$inBlockElem && !$this->mInPre ) {
2176 if ( ' ' == $t{0} and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
2177 // pre
2178 if ($this->mLastSection !== 'pre') {
2179 $paragraphStack = false;
2180 $output .= $this->closeParagraph().'<pre>';
2181 $this->mLastSection = 'pre';
2182 }
2183 $t = substr( $t, 1 );
2184 } else {
2185 // paragraph
2186 if ( '' == trim($t) ) {
2187 if ( $paragraphStack ) {
2188 $output .= $paragraphStack.'<br />';
2189 $paragraphStack = false;
2190 $this->mLastSection = 'p';
2191 } else {
2192 if ($this->mLastSection !== 'p' ) {
2193 $output .= $this->closeParagraph();
2194 $this->mLastSection = '';
2195 $paragraphStack = '<p>';
2196 } else {
2197 $paragraphStack = '</p><p>';
2198 }
2199 }
2200 } else {
2201 if ( $paragraphStack ) {
2202 $output .= $paragraphStack;
2203 $paragraphStack = false;
2204 $this->mLastSection = 'p';
2205 } else if ($this->mLastSection !== 'p') {
2206 $output .= $this->closeParagraph().'<p>';
2207 $this->mLastSection = 'p';
2208 }
2209 }
2210 }
2211 }
2212 wfProfileOut( __METHOD__."-paragraph" );
2213 }
2214 // somewhere above we forget to get out of pre block (bug 785)
2215 if($preCloseMatch && $this->mInPre) {
2216 $this->mInPre = false;
2217 }
2218 if ($paragraphStack === false) {
2219 $output .= $t."\n";
2220 }
2221 }
2222 while ( $prefixLength ) {
2223 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2224 --$prefixLength;
2225 }
2226 if ( '' != $this->mLastSection ) {
2227 $output .= '</' . $this->mLastSection . '>';
2228 $this->mLastSection = '';
2229 }
2230
2231 wfProfileOut( __METHOD__ );
2232 return $output;
2233 }
2234
2235 /**
2236 * Split up a string on ':', ignoring any occurences inside tags
2237 * to prevent illegal overlapping.
2238 * @param string $str the string to split
2239 * @param string &$before set to everything before the ':'
2240 * @param string &$after set to everything after the ':'
2241 * return string the position of the ':', or false if none found
2242 */
2243 function findColonNoLinks($str, &$before, &$after) {
2244 wfProfileIn( __METHOD__ );
2245
2246 $pos = strpos( $str, ':' );
2247 if( $pos === false ) {
2248 // Nothing to find!
2249 wfProfileOut( __METHOD__ );
2250 return false;
2251 }
2252
2253 $lt = strpos( $str, '<' );
2254 if( $lt === false || $lt > $pos ) {
2255 // Easy; no tag nesting to worry about
2256 $before = substr( $str, 0, $pos );
2257 $after = substr( $str, $pos+1 );
2258 wfProfileOut( __METHOD__ );
2259 return $pos;
2260 }
2261
2262 // Ugly state machine to walk through avoiding tags.
2263 $state = self::COLON_STATE_TEXT;
2264 $stack = 0;
2265 $len = strlen( $str );
2266 for( $i = 0; $i < $len; $i++ ) {
2267 $c = $str{$i};
2268
2269 switch( $state ) {
2270 // (Using the number is a performance hack for common cases)
2271 case 0: // self::COLON_STATE_TEXT:
2272 switch( $c ) {
2273 case "<":
2274 // Could be either a <start> tag or an </end> tag
2275 $state = self::COLON_STATE_TAGSTART;
2276 break;
2277 case ":":
2278 if( $stack == 0 ) {
2279 // We found it!
2280 $before = substr( $str, 0, $i );
2281 $after = substr( $str, $i + 1 );
2282 wfProfileOut( __METHOD__ );
2283 return $i;
2284 }
2285 // Embedded in a tag; don't break it.
2286 break;
2287 default:
2288 // Skip ahead looking for something interesting
2289 $colon = strpos( $str, ':', $i );
2290 if( $colon === false ) {
2291 // Nothing else interesting
2292 wfProfileOut( __METHOD__ );
2293 return false;
2294 }
2295 $lt = strpos( $str, '<', $i );
2296 if( $stack === 0 ) {
2297 if( $lt === false || $colon < $lt ) {
2298 // We found it!
2299 $before = substr( $str, 0, $colon );
2300 $after = substr( $str, $colon + 1 );
2301 wfProfileOut( __METHOD__ );
2302 return $i;
2303 }
2304 }
2305 if( $lt === false ) {
2306 // Nothing else interesting to find; abort!
2307 // We're nested, but there's no close tags left. Abort!
2308 break 2;
2309 }
2310 // Skip ahead to next tag start
2311 $i = $lt;
2312 $state = self::COLON_STATE_TAGSTART;
2313 }
2314 break;
2315 case 1: // self::COLON_STATE_TAG:
2316 // In a <tag>
2317 switch( $c ) {
2318 case ">":
2319 $stack++;
2320 $state = self::COLON_STATE_TEXT;
2321 break;
2322 case "/":
2323 // Slash may be followed by >?
2324 $state = self::COLON_STATE_TAGSLASH;
2325 break;
2326 default:
2327 // ignore
2328 }
2329 break;
2330 case 2: // self::COLON_STATE_TAGSTART:
2331 switch( $c ) {
2332 case "/":
2333 $state = self::COLON_STATE_CLOSETAG;
2334 break;
2335 case "!":
2336 $state = self::COLON_STATE_COMMENT;
2337 break;
2338 case ">":
2339 // Illegal early close? This shouldn't happen D:
2340 $state = self::COLON_STATE_TEXT;
2341 break;
2342 default:
2343 $state = self::COLON_STATE_TAG;
2344 }
2345 break;
2346 case 3: // self::COLON_STATE_CLOSETAG:
2347 // In a </tag>
2348 if( $c === ">" ) {
2349 $stack--;
2350 if( $stack < 0 ) {
2351 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2352 wfProfileOut( __METHOD__ );
2353 return false;
2354 }
2355 $state = self::COLON_STATE_TEXT;
2356 }
2357 break;
2358 case self::COLON_STATE_TAGSLASH:
2359 if( $c === ">" ) {
2360 // Yes, a self-closed tag <blah/>
2361 $state = self::COLON_STATE_TEXT;
2362 } else {
2363 // Probably we're jumping the gun, and this is an attribute
2364 $state = self::COLON_STATE_TAG;
2365 }
2366 break;
2367 case 5: // self::COLON_STATE_COMMENT:
2368 if( $c === "-" ) {
2369 $state = self::COLON_STATE_COMMENTDASH;
2370 }
2371 break;
2372 case self::COLON_STATE_COMMENTDASH:
2373 if( $c === "-" ) {
2374 $state = self::COLON_STATE_COMMENTDASHDASH;
2375 } else {
2376 $state = self::COLON_STATE_COMMENT;
2377 }
2378 break;
2379 case self::COLON_STATE_COMMENTDASHDASH:
2380 if( $c === ">" ) {
2381 $state = self::COLON_STATE_TEXT;
2382 } else {
2383 $state = self::COLON_STATE_COMMENT;
2384 }
2385 break;
2386 default:
2387 throw new MWException( "State machine error in " . __METHOD__ );
2388 }
2389 }
2390 if( $stack > 0 ) {
2391 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2392 return false;
2393 }
2394 wfProfileOut( __METHOD__ );
2395 return false;
2396 }
2397
2398 /**
2399 * Return value of a magic variable (like PAGENAME)
2400 *
2401 * @private
2402 */
2403 function getVariableValue( $index ) {
2404 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2405
2406 /**
2407 * Some of these require message or data lookups and can be
2408 * expensive to check many times.
2409 */
2410 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2411 if ( isset( $this->mVarCache[$index] ) ) {
2412 return $this->mVarCache[$index];
2413 }
2414 }
2415
2416 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2417 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2418
2419 # Use the time zone
2420 global $wgLocaltimezone;
2421 if ( isset( $wgLocaltimezone ) ) {
2422 $oldtz = getenv( 'TZ' );
2423 putenv( 'TZ='.$wgLocaltimezone );
2424 }
2425
2426 wfSuppressWarnings(); // E_STRICT system time bitching
2427 $localTimestamp = date( 'YmdHis', $ts );
2428 $localMonth = date( 'm', $ts );
2429 $localMonthName = date( 'n', $ts );
2430 $localDay = date( 'j', $ts );
2431 $localDay2 = date( 'd', $ts );
2432 $localDayOfWeek = date( 'w', $ts );
2433 $localWeek = date( 'W', $ts );
2434 $localYear = date( 'Y', $ts );
2435 $localHour = date( 'H', $ts );
2436 if ( isset( $wgLocaltimezone ) ) {
2437 putenv( 'TZ='.$oldtz );
2438 }
2439 wfRestoreWarnings();
2440
2441 switch ( $index ) {
2442 case 'currentmonth':
2443 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2444 case 'currentmonthname':
2445 return $this->mVarCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2446 case 'currentmonthnamegen':
2447 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2448 case 'currentmonthabbrev':
2449 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2450 case 'currentday':
2451 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2452 case 'currentday2':
2453 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2454 case 'localmonth':
2455 return $this->mVarCache[$index] = $wgContLang->formatNum( $localMonth );
2456 case 'localmonthname':
2457 return $this->mVarCache[$index] = $wgContLang->getMonthName( $localMonthName );
2458 case 'localmonthnamegen':
2459 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2460 case 'localmonthabbrev':
2461 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2462 case 'localday':
2463 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay );
2464 case 'localday2':
2465 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay2 );
2466 case 'pagename':
2467 return wfEscapeWikiText( $this->mTitle->getText() );
2468 case 'pagenamee':
2469 return $this->mTitle->getPartialURL();
2470 case 'fullpagename':
2471 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2472 case 'fullpagenamee':
2473 return $this->mTitle->getPrefixedURL();
2474 case 'subpagename':
2475 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2476 case 'subpagenamee':
2477 return $this->mTitle->getSubpageUrlForm();
2478 case 'basepagename':
2479 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2480 case 'basepagenamee':
2481 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2482 case 'talkpagename':
2483 if( $this->mTitle->canTalk() ) {
2484 $talkPage = $this->mTitle->getTalkPage();
2485 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2486 } else {
2487 return '';
2488 }
2489 case 'talkpagenamee':
2490 if( $this->mTitle->canTalk() ) {
2491 $talkPage = $this->mTitle->getTalkPage();
2492 return $talkPage->getPrefixedUrl();
2493 } else {
2494 return '';
2495 }
2496 case 'subjectpagename':
2497 $subjPage = $this->mTitle->getSubjectPage();
2498 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2499 case 'subjectpagenamee':
2500 $subjPage = $this->mTitle->getSubjectPage();
2501 return $subjPage->getPrefixedUrl();
2502 case 'revisionid':
2503 // Let the edit saving system know we should parse the page
2504 // *after* a revision ID has been assigned.
2505 $this->mOutput->setFlag( 'vary-revision' );
2506 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2507 return $this->mRevisionId;
2508 case 'revisionday':
2509 // Let the edit saving system know we should parse the page
2510 // *after* a revision ID has been assigned. This is for null edits.
2511 $this->mOutput->setFlag( 'vary-revision' );
2512 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2513 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2514 case 'revisionday2':
2515 // Let the edit saving system know we should parse the page
2516 // *after* a revision ID has been assigned. This is for null edits.
2517 $this->mOutput->setFlag( 'vary-revision' );
2518 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2519 return substr( $this->getRevisionTimestamp(), 6, 2 );
2520 case 'revisionmonth':
2521 // Let the edit saving system know we should parse the page
2522 // *after* a revision ID has been assigned. This is for null edits.
2523 $this->mOutput->setFlag( 'vary-revision' );
2524 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2525 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2526 case 'revisionyear':
2527 // Let the edit saving system know we should parse the page
2528 // *after* a revision ID has been assigned. This is for null edits.
2529 $this->mOutput->setFlag( 'vary-revision' );
2530 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2531 return substr( $this->getRevisionTimestamp(), 0, 4 );
2532 case 'revisiontimestamp':
2533 // Let the edit saving system know we should parse the page
2534 // *after* a revision ID has been assigned. This is for null edits.
2535 $this->mOutput->setFlag( 'vary-revision' );
2536 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2537 return $this->getRevisionTimestamp();
2538 case 'namespace':
2539 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2540 case 'namespacee':
2541 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2542 case 'talkspace':
2543 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2544 case 'talkspacee':
2545 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2546 case 'subjectspace':
2547 return $this->mTitle->getSubjectNsText();
2548 case 'subjectspacee':
2549 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2550 case 'currentdayname':
2551 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2552 case 'currentyear':
2553 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2554 case 'currenttime':
2555 return $this->mVarCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2556 case 'currenthour':
2557 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2558 case 'currentweek':
2559 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2560 // int to remove the padding
2561 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2562 case 'currentdow':
2563 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2564 case 'localdayname':
2565 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2566 case 'localyear':
2567 return $this->mVarCache[$index] = $wgContLang->formatNum( $localYear, true );
2568 case 'localtime':
2569 return $this->mVarCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2570 case 'localhour':
2571 return $this->mVarCache[$index] = $wgContLang->formatNum( $localHour, true );
2572 case 'localweek':
2573 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2574 // int to remove the padding
2575 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2576 case 'localdow':
2577 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2578 case 'numberofarticles':
2579 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2580 case 'numberoffiles':
2581 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2582 case 'numberofusers':
2583 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2584 case 'numberofpages':
2585 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2586 case 'numberofadmins':
2587 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
2588 case 'numberofedits':
2589 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2590 case 'currenttimestamp':
2591 return $this->mVarCache[$index] = wfTimestamp( TS_MW, $ts );
2592 case 'localtimestamp':
2593 return $this->mVarCache[$index] = $localTimestamp;
2594 case 'currentversion':
2595 return $this->mVarCache[$index] = SpecialVersion::getVersion();
2596 case 'sitename':
2597 return $wgSitename;
2598 case 'server':
2599 return $wgServer;
2600 case 'servername':
2601 return $wgServerName;
2602 case 'scriptpath':
2603 return $wgScriptPath;
2604 case 'directionmark':
2605 return $wgContLang->getDirMark();
2606 case 'contentlanguage':
2607 global $wgContLanguageCode;
2608 return $wgContLanguageCode;
2609 default:
2610 $ret = null;
2611 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret ) ) )
2612 return $ret;
2613 else
2614 return null;
2615 }
2616 }
2617
2618 /**
2619 * initialise the magic variables (like CURRENTMONTHNAME)
2620 *
2621 * @private
2622 */
2623 function initialiseVariables() {
2624 wfProfileIn( __METHOD__ );
2625 $variableIDs = MagicWord::getVariableIDs();
2626
2627 $this->mVariables = new MagicWordArray( $variableIDs );
2628 wfProfileOut( __METHOD__ );
2629 }
2630
2631 /**
2632 * Preprocess some wikitext and return the document tree.
2633 * This is the ghost of replace_variables().
2634 *
2635 * @param string $text The text to parse
2636 * @param integer flags Bitwise combination of:
2637 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2638 * included. Default is to assume a direct page view.
2639 *
2640 * The generated DOM tree must depend only on the input text and the flags.
2641 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2642 *
2643 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2644 * change in the DOM tree for a given text, must be passed through the section identifier
2645 * in the section edit link and thus back to extractSections().
2646 *
2647 * The output of this function is currently only cached in process memory, but a persistent
2648 * cache may be implemented at a later date which takes further advantage of these strict
2649 * dependency requirements.
2650 *
2651 * @private
2652 */
2653 function preprocessToDom ( $text, $flags = 0 ) {
2654 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2655 return $dom;
2656 }
2657
2658 /*
2659 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2660 */
2661 public static function splitWhitespace( $s ) {
2662 $ltrimmed = ltrim( $s );
2663 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2664 $trimmed = rtrim( $ltrimmed );
2665 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2666 if ( $diff > 0 ) {
2667 $w2 = substr( $ltrimmed, -$diff );
2668 } else {
2669 $w2 = '';
2670 }
2671 return array( $w1, $trimmed, $w2 );
2672 }
2673
2674 /**
2675 * Replace magic variables, templates, and template arguments
2676 * with the appropriate text. Templates are substituted recursively,
2677 * taking care to avoid infinite loops.
2678 *
2679 * Note that the substitution depends on value of $mOutputType:
2680 * self::OT_WIKI: only {{subst:}} templates
2681 * self::OT_PREPROCESS: templates but not extension tags
2682 * self::OT_HTML: all templates and extension tags
2683 *
2684 * @param string $tex The text to transform
2685 * @param PPFrame $frame Object describing the arguments passed to the template.
2686 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2687 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2688 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2689 * @private
2690 */
2691 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2692 # Prevent too big inclusions
2693 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2694 return $text;
2695 }
2696
2697 wfProfileIn( __METHOD__ );
2698
2699 if ( $frame === false ) {
2700 $frame = $this->getPreprocessor()->newFrame();
2701 } elseif ( !( $frame instanceof PPFrame ) ) {
2702 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2703 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2704 }
2705
2706 $dom = $this->preprocessToDom( $text );
2707 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2708 $text = $frame->expand( $dom, $flags );
2709
2710 wfProfileOut( __METHOD__ );
2711 return $text;
2712 }
2713
2714 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2715 static function createAssocArgs( $args ) {
2716 $assocArgs = array();
2717 $index = 1;
2718 foreach( $args as $arg ) {
2719 $eqpos = strpos( $arg, '=' );
2720 if ( $eqpos === false ) {
2721 $assocArgs[$index++] = $arg;
2722 } else {
2723 $name = trim( substr( $arg, 0, $eqpos ) );
2724 $value = trim( substr( $arg, $eqpos+1 ) );
2725 if ( $value === false ) {
2726 $value = '';
2727 }
2728 if ( $name !== false ) {
2729 $assocArgs[$name] = $value;
2730 }
2731 }
2732 }
2733
2734 return $assocArgs;
2735 }
2736
2737 /**
2738 * Warn the user when a parser limitation is reached
2739 * Will warn at most once the user per limitation type
2740 *
2741 * @param string $limitationType, should be one of:
2742 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2743 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2744 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2745 * @params int $current, $max When an explicit limit has been
2746 * exceeded, provide the values (optional)
2747 */
2748 function limitationWarn( $limitationType, $current=null, $max=null) {
2749 $msgName = $limitationType . '-warning';
2750 //does no harm if $current and $max are present but are unnecessary for the message
2751 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2752 $this->mOutput->addWarning( $warning );
2753 $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
2754 if ( $cat ) {
2755 $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2756 }
2757 }
2758
2759 /**
2760 * Return the text of a template, after recursively
2761 * replacing any variables or templates within the template.
2762 *
2763 * @param array $piece The parts of the template
2764 * $piece['title']: the title, i.e. the part before the |
2765 * $piece['parts']: the parameter array
2766 * $piece['lineStart']: whether the brace was at the start of a line
2767 * @param PPFrame The current frame, contains template arguments
2768 * @return string the text of the template
2769 * @private
2770 */
2771 function braceSubstitution( $piece, $frame ) {
2772 global $wgContLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2773 wfProfileIn( __METHOD__ );
2774 wfProfileIn( __METHOD__.'-setup' );
2775
2776 # Flags
2777 $found = false; # $text has been filled
2778 $nowiki = false; # wiki markup in $text should be escaped
2779 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2780 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2781 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2782 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2783
2784 # Title object, where $text came from
2785 $title = NULL;
2786
2787 # $part1 is the bit before the first |, and must contain only title characters.
2788 # Various prefixes will be stripped from it later.
2789 $titleWithSpaces = $frame->expand( $piece['title'] );
2790 $part1 = trim( $titleWithSpaces );
2791 $titleText = false;
2792
2793 # Original title text preserved for various purposes
2794 $originalTitle = $part1;
2795
2796 # $args is a list of argument nodes, starting from index 0, not including $part1
2797 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2798 wfProfileOut( __METHOD__.'-setup' );
2799
2800 # SUBST
2801 wfProfileIn( __METHOD__.'-modifiers' );
2802 if ( !$found ) {
2803 $mwSubst = MagicWord::get( 'subst' );
2804 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2805 # One of two possibilities is true:
2806 # 1) Found SUBST but not in the PST phase
2807 # 2) Didn't find SUBST and in the PST phase
2808 # In either case, return without further processing
2809 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2810 $isLocalObj = true;
2811 $found = true;
2812 }
2813 }
2814
2815 # Variables
2816 if ( !$found && $args->getLength() == 0 ) {
2817 $id = $this->mVariables->matchStartToEnd( $part1 );
2818 if ( $id !== false ) {
2819 $text = $this->getVariableValue( $id );
2820 if (MagicWord::getCacheTTL($id)>-1)
2821 $this->mOutput->mContainsOldMagic = true;
2822 $found = true;
2823 }
2824 }
2825
2826 # MSG, MSGNW and RAW
2827 if ( !$found ) {
2828 # Check for MSGNW:
2829 $mwMsgnw = MagicWord::get( 'msgnw' );
2830 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2831 $nowiki = true;
2832 } else {
2833 # Remove obsolete MSG:
2834 $mwMsg = MagicWord::get( 'msg' );
2835 $mwMsg->matchStartAndRemove( $part1 );
2836 }
2837
2838 # Check for RAW:
2839 $mwRaw = MagicWord::get( 'raw' );
2840 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2841 $forceRawInterwiki = true;
2842 }
2843 }
2844 wfProfileOut( __METHOD__.'-modifiers' );
2845
2846 # Parser functions
2847 if ( !$found ) {
2848 wfProfileIn( __METHOD__ . '-pfunc' );
2849
2850 $colonPos = strpos( $part1, ':' );
2851 if ( $colonPos !== false ) {
2852 # Case sensitive functions
2853 $function = substr( $part1, 0, $colonPos );
2854 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2855 $function = $this->mFunctionSynonyms[1][$function];
2856 } else {
2857 # Case insensitive functions
2858 $function = strtolower( $function );
2859 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2860 $function = $this->mFunctionSynonyms[0][$function];
2861 } else {
2862 $function = false;
2863 }
2864 }
2865 if ( $function ) {
2866 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2867 $initialArgs = array( &$this );
2868 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2869 if ( $flags & SFH_OBJECT_ARGS ) {
2870 # Add a frame parameter, and pass the arguments as an array
2871 $allArgs = $initialArgs;
2872 $allArgs[] = $frame;
2873 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2874 $funcArgs[] = $args->item( $i );
2875 }
2876 $allArgs[] = $funcArgs;
2877 } else {
2878 # Convert arguments to plain text
2879 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2880 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2881 }
2882 $allArgs = array_merge( $initialArgs, $funcArgs );
2883 }
2884
2885 # Workaround for PHP bug 35229 and similar
2886 if ( !is_callable( $callback ) ) {
2887 throw new MWException( "Tag hook for $function is not callable\n" );
2888 }
2889 $result = call_user_func_array( $callback, $allArgs );
2890 $found = true;
2891 $noparse = true;
2892 $preprocessFlags = 0;
2893
2894 if ( is_array( $result ) ) {
2895 if ( isset( $result[0] ) ) {
2896 $text = $result[0];
2897 unset( $result[0] );
2898 }
2899
2900 // Extract flags into the local scope
2901 // This allows callers to set flags such as nowiki, found, etc.
2902 extract( $result );
2903 } else {
2904 $text = $result;
2905 }
2906 if ( !$noparse ) {
2907 $text = $this->preprocessToDom( $text, $preprocessFlags );
2908 $isChildObj = true;
2909 }
2910 }
2911 }
2912 wfProfileOut( __METHOD__ . '-pfunc' );
2913 }
2914
2915 # Finish mangling title and then check for loops.
2916 # Set $title to a Title object and $titleText to the PDBK
2917 if ( !$found ) {
2918 $ns = NS_TEMPLATE;
2919 # Split the title into page and subpage
2920 $subpage = '';
2921 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2922 if ($subpage !== '') {
2923 $ns = $this->mTitle->getNamespace();
2924 }
2925 $title = Title::newFromText( $part1, $ns );
2926 if ( $title ) {
2927 $titleText = $title->getPrefixedText();
2928 # Check for language variants if the template is not found
2929 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2930 $wgContLang->findVariantLink( $part1, $title, true );
2931 }
2932 # Do infinite loop check
2933 if ( !$frame->loopCheck( $title ) ) {
2934 $found = true;
2935 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2936 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2937 }
2938 # Do recursion depth check
2939 $limit = $this->mOptions->getMaxTemplateDepth();
2940 if ( $frame->depth >= $limit ) {
2941 $found = true;
2942 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2943 }
2944 }
2945 }
2946
2947 # Load from database
2948 if ( !$found && $title ) {
2949 wfProfileIn( __METHOD__ . '-loadtpl' );
2950 if ( !$title->isExternal() ) {
2951 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2952 $text = SpecialPage::capturePath( $title );
2953 if ( is_string( $text ) ) {
2954 $found = true;
2955 $isHTML = true;
2956 $this->disableCache();
2957 }
2958 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2959 $found = false; //access denied
2960 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
2961 } else {
2962 list( $text, $title ) = $this->getTemplateDom( $title );
2963 if ( $text !== false ) {
2964 $found = true;
2965 $isChildObj = true;
2966 }
2967 }
2968
2969 # If the title is valid but undisplayable, make a link to it
2970 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2971 $text = "[[:$titleText]]";
2972 $found = true;
2973 }
2974 } elseif ( $title->isTrans() ) {
2975 // Interwiki transclusion
2976 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2977 $text = $this->interwikiTransclude( $title, 'render' );
2978 $isHTML = true;
2979 } else {
2980 $text = $this->interwikiTransclude( $title, 'raw' );
2981 // Preprocess it like a template
2982 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2983 $isChildObj = true;
2984 }
2985 $found = true;
2986 }
2987 wfProfileOut( __METHOD__ . '-loadtpl' );
2988 }
2989
2990 # If we haven't found text to substitute by now, we're done
2991 # Recover the source wikitext and return it
2992 if ( !$found ) {
2993 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2994 wfProfileOut( __METHOD__ );
2995 return array( 'object' => $text );
2996 }
2997
2998 # Expand DOM-style return values in a child frame
2999 if ( $isChildObj ) {
3000 # Clean up argument array
3001 $newFrame = $frame->newChild( $args, $title );
3002
3003 if ( $nowiki ) {
3004 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3005 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3006 # Expansion is eligible for the empty-frame cache
3007 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3008 $text = $this->mTplExpandCache[$titleText];
3009 } else {
3010 $text = $newFrame->expand( $text );
3011 $this->mTplExpandCache[$titleText] = $text;
3012 }
3013 } else {
3014 # Uncached expansion
3015 $text = $newFrame->expand( $text );
3016 }
3017 }
3018 if ( $isLocalObj && $nowiki ) {
3019 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3020 $isLocalObj = false;
3021 }
3022
3023 # Replace raw HTML by a placeholder
3024 # Add a blank line preceding, to prevent it from mucking up
3025 # immediately preceding headings
3026 if ( $isHTML ) {
3027 $text = "\n\n" . $this->insertStripItem( $text );
3028 }
3029 # Escape nowiki-style return values
3030 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3031 $text = wfEscapeWikiText( $text );
3032 }
3033 # Bug 529: if the template begins with a table or block-level
3034 # element, it should be treated as beginning a new line.
3035 # This behaviour is somewhat controversial.
3036 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3037 $text = "\n" . $text;
3038 }
3039
3040 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3041 # Error, oversize inclusion
3042 $text = "[[$originalTitle]]" .
3043 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3044 $this->limitationWarn( 'post-expand-template-inclusion' );
3045 }
3046
3047 if ( $isLocalObj ) {
3048 $ret = array( 'object' => $text );
3049 } else {
3050 $ret = array( 'text' => $text );
3051 }
3052
3053 wfProfileOut( __METHOD__ );
3054 return $ret;
3055 }
3056
3057 /**
3058 * Get the semi-parsed DOM representation of a template with a given title,
3059 * and its redirect destination title. Cached.
3060 */
3061 function getTemplateDom( $title ) {
3062 $cacheTitle = $title;
3063 $titleText = $title->getPrefixedDBkey();
3064
3065 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3066 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3067 $title = Title::makeTitle( $ns, $dbk );
3068 $titleText = $title->getPrefixedDBkey();
3069 }
3070 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3071 return array( $this->mTplDomCache[$titleText], $title );
3072 }
3073
3074 // Cache miss, go to the database
3075 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3076
3077 if ( $text === false ) {
3078 $this->mTplDomCache[$titleText] = false;
3079 return array( false, $title );
3080 }
3081
3082 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3083 $this->mTplDomCache[ $titleText ] = $dom;
3084
3085 if (! $title->equals($cacheTitle)) {
3086 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3087 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3088 }
3089
3090 return array( $dom, $title );
3091 }
3092
3093 /**
3094 * Fetch the unparsed text of a template and register a reference to it.
3095 */
3096 function fetchTemplateAndTitle( $title ) {
3097 $templateCb = $this->mOptions->getTemplateCallback();
3098 $stuff = call_user_func( $templateCb, $title, $this );
3099 $text = $stuff['text'];
3100 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3101 if ( isset( $stuff['deps'] ) ) {
3102 foreach ( $stuff['deps'] as $dep ) {
3103 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3104 }
3105 }
3106 return array($text,$finalTitle);
3107 }
3108
3109 function fetchTemplate( $title ) {
3110 $rv = $this->fetchTemplateAndTitle($title);
3111 return $rv[0];
3112 }
3113
3114 /**
3115 * Static function to get a template
3116 * Can be overridden via ParserOptions::setTemplateCallback().
3117 */
3118 static function statelessFetchTemplate( $title, $parser=false ) {
3119 $text = $skip = false;
3120 $finalTitle = $title;
3121 $deps = array();
3122
3123 // Loop to fetch the article, with up to 1 redirect
3124 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3125 # Give extensions a chance to select the revision instead
3126 $id = false; // Assume current
3127 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3128
3129 if( $skip ) {
3130 $text = false;
3131 $deps[] = array(
3132 'title' => $title,
3133 'page_id' => $title->getArticleID(),
3134 'rev_id' => null );
3135 break;
3136 }
3137 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3138 $rev_id = $rev ? $rev->getId() : 0;
3139 // If there is no current revision, there is no page
3140 if( $id === false && !$rev ) {
3141 $linkCache = LinkCache::singleton();
3142 $linkCache->addBadLinkObj( $title );
3143 }
3144
3145 $deps[] = array(
3146 'title' => $title,
3147 'page_id' => $title->getArticleID(),
3148 'rev_id' => $rev_id );
3149
3150 if( $rev ) {
3151 $text = $rev->getText();
3152 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3153 global $wgContLang;
3154 $message = $wgContLang->lcfirst( $title->getText() );
3155 $text = wfMsgForContentNoTrans( $message );
3156 if( wfEmptyMsg( $message, $text ) ) {
3157 $text = false;
3158 break;
3159 }
3160 } else {
3161 break;
3162 }
3163 if ( $text === false ) {
3164 break;
3165 }
3166 // Redirect?
3167 $finalTitle = $title;
3168 $title = Title::newFromRedirect( $text );
3169 }
3170 return array(
3171 'text' => $text,
3172 'finalTitle' => $finalTitle,
3173 'deps' => $deps );
3174 }
3175
3176 /**
3177 * Transclude an interwiki link.
3178 */
3179 function interwikiTransclude( $title, $action ) {
3180 global $wgEnableScaryTranscluding;
3181
3182 if (!$wgEnableScaryTranscluding)
3183 return wfMsg('scarytranscludedisabled');
3184
3185 $url = $title->getFullUrl( "action=$action" );
3186
3187 if (strlen($url) > 255)
3188 return wfMsg('scarytranscludetoolong');
3189 return $this->fetchScaryTemplateMaybeFromCache($url);
3190 }
3191
3192 function fetchScaryTemplateMaybeFromCache($url) {
3193 global $wgTranscludeCacheExpiry;
3194 $dbr = wfGetDB(DB_SLAVE);
3195 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3196 array('tc_url' => $url));
3197 if ($obj) {
3198 $time = $obj->tc_time;
3199 $text = $obj->tc_contents;
3200 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3201 return $text;
3202 }
3203 }
3204
3205 $text = Http::get($url);
3206 if (!$text)
3207 return wfMsg('scarytranscludefailed', $url);
3208
3209 $dbw = wfGetDB(DB_MASTER);
3210 $dbw->replace('transcache', array('tc_url'), array(
3211 'tc_url' => $url,
3212 'tc_time' => time(),
3213 'tc_contents' => $text));
3214 return $text;
3215 }
3216
3217
3218 /**
3219 * Triple brace replacement -- used for template arguments
3220 * @private
3221 */
3222 function argSubstitution( $piece, $frame ) {
3223 wfProfileIn( __METHOD__ );
3224
3225 $error = false;
3226 $parts = $piece['parts'];
3227 $nameWithSpaces = $frame->expand( $piece['title'] );
3228 $argName = trim( $nameWithSpaces );
3229 $object = false;
3230 $text = $frame->getArgument( $argName );
3231 if ( $text === false && $parts->getLength() > 0
3232 && (
3233 $this->ot['html']
3234 || $this->ot['pre']
3235 || ( $this->ot['wiki'] && $frame->isTemplate() )
3236 )
3237 ) {
3238 # No match in frame, use the supplied default
3239 $object = $parts->item( 0 )->getChildren();
3240 }
3241 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3242 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3243 $this->limitationWarn( 'post-expand-template-argument' );
3244 }
3245
3246 if ( $text === false && $object === false ) {
3247 # No match anywhere
3248 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3249 }
3250 if ( $error !== false ) {
3251 $text .= $error;
3252 }
3253 if ( $object !== false ) {
3254 $ret = array( 'object' => $object );
3255 } else {
3256 $ret = array( 'text' => $text );
3257 }
3258
3259 wfProfileOut( __METHOD__ );
3260 return $ret;
3261 }
3262
3263 /**
3264 * Return the text to be used for a given extension tag.
3265 * This is the ghost of strip().
3266 *
3267 * @param array $params Associative array of parameters:
3268 * name PPNode for the tag name
3269 * attr PPNode for unparsed text where tag attributes are thought to be
3270 * attributes Optional associative array of parsed attributes
3271 * inner Contents of extension element
3272 * noClose Original text did not have a close tag
3273 * @param PPFrame $frame
3274 */
3275 function extensionSubstitution( $params, $frame ) {
3276 global $wgRawHtml, $wgContLang;
3277
3278 $name = $frame->expand( $params['name'] );
3279 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3280 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3281
3282 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3283
3284 if ( $this->ot['html'] ) {
3285 $name = strtolower( $name );
3286
3287 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3288 if ( isset( $params['attributes'] ) ) {
3289 $attributes = $attributes + $params['attributes'];
3290 }
3291 switch ( $name ) {
3292 case 'html':
3293 if( $wgRawHtml ) {
3294 $output = $content;
3295 break;
3296 } else {
3297 throw new MWException( '<html> extension tag encountered unexpectedly' );
3298 }
3299 case 'nowiki':
3300 $output = Xml::escapeTagsOnly( $content );
3301 break;
3302 case 'math':
3303 $output = $wgContLang->armourMath(
3304 MathRenderer::renderMath( $content, $attributes ) );
3305 break;
3306 case 'gallery':
3307 $output = $this->renderImageGallery( $content, $attributes );
3308 break;
3309 case 'poem':
3310 $output = $this->renderPoem( $content, $attributes );
3311 break;
3312 default:
3313 if( isset( $this->mTagHooks[$name] ) ) {
3314 # Workaround for PHP bug 35229 and similar
3315 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3316 throw new MWException( "Tag hook for $name is not callable\n" );
3317 }
3318 $output = call_user_func_array( $this->mTagHooks[$name],
3319 array( $content, $attributes, $this ) );
3320 } else {
3321 $output = '<span class="error">Invalid tag extension name: ' .
3322 htmlspecialchars( $name ) . '</span>';
3323 }
3324 }
3325 } else {
3326 if ( is_null( $attrText ) ) {
3327 $attrText = '';
3328 }
3329 if ( isset( $params['attributes'] ) ) {
3330 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3331 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3332 htmlspecialchars( $attrValue ) . '"';
3333 }
3334 }
3335 if ( $content === null ) {
3336 $output = "<$name$attrText/>";
3337 } else {
3338 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3339 $output = "<$name$attrText>$content$close";
3340 }
3341 }
3342
3343 if ( $name === 'html' || $name === 'nowiki' ) {
3344 $this->mStripState->nowiki->setPair( $marker, $output );
3345 } else {
3346 $this->mStripState->general->setPair( $marker, $output );
3347 }
3348 return $marker;
3349 }
3350
3351 /**
3352 * Increment an include size counter
3353 *
3354 * @param string $type The type of expansion
3355 * @param integer $size The size of the text
3356 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3357 */
3358 function incrementIncludeSize( $type, $size ) {
3359 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3360 return false;
3361 } else {
3362 $this->mIncludeSizes[$type] += $size;
3363 return true;
3364 }
3365 }
3366
3367 /**
3368 * Increment the expensive function count
3369 *
3370 * @return boolean False if the limit has been exceeded
3371 */
3372 function incrementExpensiveFunctionCount() {
3373 global $wgExpensiveParserFunctionLimit;
3374 $this->mExpensiveFunctionCount++;
3375 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3376 return true;
3377 }
3378 return false;
3379 }
3380
3381 /**
3382 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3383 * Fills $this->mDoubleUnderscores, returns the modified text
3384 */
3385 function doDoubleUnderscore( $text ) {
3386 // The position of __TOC__ needs to be recorded
3387 $mw = MagicWord::get( 'toc' );
3388 if( $mw->match( $text ) ) {
3389 $this->mShowToc = true;
3390 $this->mForceTocPosition = true;
3391
3392 // Set a placeholder. At the end we'll fill it in with the TOC.
3393 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3394
3395 // Only keep the first one.
3396 $text = $mw->replace( '', $text );
3397 }
3398
3399 // Now match and remove the rest of them
3400 $mwa = MagicWord::getDoubleUnderscoreArray();
3401 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3402
3403 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3404 $this->mOutput->mNoGallery = true;
3405 }
3406 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3407 $this->mShowToc = false;
3408 }
3409 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3410 $this->mOutput->setProperty( 'hiddencat', 'y' );
3411
3412 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
3413 if ( $containerCategory ) {
3414 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3415 } else {
3416 wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3417 }
3418 }
3419 # (bug 8068) Allow control over whether robots index a page.
3420 #
3421 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3422 # is not desirable, the last one on the page should win.
3423 if( isset( $this->mDoubleUnderscores['noindex'] ) ) {
3424 $this->mOutput->setIndexPolicy( 'noindex' );
3425 } elseif( isset( $this->mDoubleUnderscores['index'] ) ) {
3426 $this->mOutput->setIndexPolicy( 'index' );
3427 }
3428
3429 return $text;
3430 }
3431
3432 /**
3433 * This function accomplishes several tasks:
3434 * 1) Auto-number headings if that option is enabled
3435 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3436 * 3) Add a Table of contents on the top for users who have enabled the option
3437 * 4) Auto-anchor headings
3438 *
3439 * It loops through all headlines, collects the necessary data, then splits up the
3440 * string and re-inserts the newly formatted headlines.
3441 *
3442 * @param string $text
3443 * @param boolean $isMain
3444 * @private
3445 */
3446 function formatHeadings( $text, $isMain=true ) {
3447 global $wgMaxTocLevel, $wgContLang;
3448
3449 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3450 $showEditLink = $this->mOptions->getEditSection();
3451
3452 // Do not call quickUserCan unless necessary
3453 if( $showEditLink && !$this->mTitle->quickUserCan( 'edit' ) ) {
3454 $showEditLink = 0;
3455 }
3456
3457 # Inhibit editsection links if requested in the page
3458 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3459 $showEditLink = 0;
3460 }
3461
3462 # Get all headlines for numbering them and adding funky stuff like [edit]
3463 # links - this is for later, but we need the number of headlines right now
3464 $matches = array();
3465 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3466
3467 # if there are fewer than 4 headlines in the article, do not show TOC
3468 # unless it's been explicitly enabled.
3469 $enoughToc = $this->mShowToc &&
3470 (($numMatches >= 4) || $this->mForceTocPosition);
3471
3472 # Allow user to stipulate that a page should have a "new section"
3473 # link added via __NEWSECTIONLINK__
3474 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3475 $this->mOutput->setNewSection( true );
3476 }
3477
3478 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3479 # override above conditions and always show TOC above first header
3480 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3481 $this->mShowToc = true;
3482 $enoughToc = true;
3483 }
3484
3485 # We need this to perform operations on the HTML
3486 $sk = $this->mOptions->getSkin();
3487
3488 # headline counter
3489 $headlineCount = 0;
3490 $numVisible = 0;
3491
3492 # Ugh .. the TOC should have neat indentation levels which can be
3493 # passed to the skin functions. These are determined here
3494 $toc = '';
3495 $full = '';
3496 $head = array();
3497 $sublevelCount = array();
3498 $levelCount = array();
3499 $toclevel = 0;
3500 $level = 0;
3501 $prevlevel = 0;
3502 $toclevel = 0;
3503 $prevtoclevel = 0;
3504 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3505 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3506 $tocraw = array();
3507
3508 foreach( $matches[3] as $headline ) {
3509 $isTemplate = false;
3510 $titleText = false;
3511 $sectionIndex = false;
3512 $numbering = '';
3513 $markerMatches = array();
3514 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3515 $serial = $markerMatches[1];
3516 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3517 $isTemplate = ($titleText != $baseTitleText);
3518 $headline = preg_replace("/^$markerRegex/", "", $headline);
3519 }
3520
3521 if( $toclevel ) {
3522 $prevlevel = $level;
3523 $prevtoclevel = $toclevel;
3524 }
3525 $level = $matches[1][$headlineCount];
3526
3527 if( $doNumberHeadings || $enoughToc ) {
3528
3529 if ( $level > $prevlevel ) {
3530 # Increase TOC level
3531 $toclevel++;
3532 $sublevelCount[$toclevel] = 0;
3533 if( $toclevel<$wgMaxTocLevel ) {
3534 $prevtoclevel = $toclevel;
3535 $toc .= $sk->tocIndent();
3536 $numVisible++;
3537 }
3538 }
3539 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3540 # Decrease TOC level, find level to jump to
3541
3542 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3543 # Can only go down to level 1
3544 $toclevel = 1;
3545 } else {
3546 for ($i = $toclevel; $i > 0; $i--) {
3547 if ( $levelCount[$i] == $level ) {
3548 # Found last matching level
3549 $toclevel = $i;
3550 break;
3551 }
3552 elseif ( $levelCount[$i] < $level ) {
3553 # Found first matching level below current level
3554 $toclevel = $i + 1;
3555 break;
3556 }
3557 }
3558 }
3559 if( $toclevel<$wgMaxTocLevel ) {
3560 if($prevtoclevel < $wgMaxTocLevel) {
3561 # Unindent only if the previous toc level was shown :p
3562 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3563 $prevtoclevel = $toclevel;
3564 } else {
3565 $toc .= $sk->tocLineEnd();
3566 }
3567 }
3568 }
3569 else {
3570 # No change in level, end TOC line
3571 if( $toclevel<$wgMaxTocLevel ) {
3572 $toc .= $sk->tocLineEnd();
3573 }
3574 }
3575
3576 $levelCount[$toclevel] = $level;
3577
3578 # count number of headlines for each level
3579 @$sublevelCount[$toclevel]++;
3580 $dot = 0;
3581 for( $i = 1; $i <= $toclevel; $i++ ) {
3582 if( !empty( $sublevelCount[$i] ) ) {
3583 if( $dot ) {
3584 $numbering .= '.';
3585 }
3586 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3587 $dot = 1;
3588 }
3589 }
3590 }
3591
3592 # The safe header is a version of the header text safe to use for links
3593 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3594 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3595
3596 # Remove link placeholders by the link text.
3597 # <!--LINK number-->
3598 # turns into
3599 # link text with suffix
3600 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3601
3602 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3603 $tocline = preg_replace(
3604 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3605 array( '', '<$1>'),
3606 $safeHeadline
3607 );
3608 $tocline = trim( $tocline );
3609
3610 # For the anchor, strip out HTML-y stuff period
3611 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3612 $safeHeadline = trim( $safeHeadline );
3613
3614 # Save headline for section edit hint before it's escaped
3615 $headlineHint = $safeHeadline;
3616 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3617 # HTML names must be case-insensitively unique (bug 10721)
3618 $arrayKey = strtolower( $safeHeadline );
3619
3620 # count how many in assoc. array so we can track dupes in anchors
3621 isset( $refers[$arrayKey] ) ? $refers[$arrayKey]++ : $refers[$arrayKey] = 1;
3622 $refcount[$headlineCount] = $refers[$arrayKey];
3623
3624 # Don't number the heading if it is the only one (looks silly)
3625 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3626 # the two are different if the line contains a link
3627 $headline=$numbering . ' ' . $headline;
3628 }
3629
3630 # Create the anchor for linking from the TOC to the section
3631 $anchor = $safeHeadline;
3632 if($refcount[$headlineCount] > 1 ) {
3633 $anchor .= '_' . $refcount[$headlineCount];
3634 }
3635 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3636 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3637 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3638 }
3639 # give headline the correct <h#> tag
3640 if( $showEditLink && $sectionIndex !== false ) {
3641 if( $isTemplate ) {
3642 # Put a T flag in the section identifier, to indicate to extractSections()
3643 # that sections inside <includeonly> should be counted.
3644 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3645 } else {
3646 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3647 }
3648 } else {
3649 $editlink = '';
3650 }
3651 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3652
3653 $headlineCount++;
3654 }
3655
3656 $this->mOutput->setSections( $tocraw );
3657
3658 # Never ever show TOC if no headers
3659 if( $numVisible < 1 ) {
3660 $enoughToc = false;
3661 }
3662
3663 if( $enoughToc ) {
3664 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3665 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3666 }
3667 $toc = $sk->tocList( $toc );
3668 }
3669
3670 # split up and insert constructed headlines
3671
3672 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3673 $i = 0;
3674
3675 foreach( $blocks as $block ) {
3676 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3677 # This is the [edit] link that appears for the top block of text when
3678 # section editing is enabled
3679
3680 # Disabled because it broke block formatting
3681 # For example, a bullet point in the top line
3682 # $full .= $sk->editSectionLink(0);
3683 }
3684 $full .= $block;
3685 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3686 # Top anchor now in skin
3687 $full = $full.$toc;
3688 }
3689
3690 if( !empty( $head[$i] ) ) {
3691 $full .= $head[$i];
3692 }
3693 $i++;
3694 }
3695 if( $this->mForceTocPosition ) {
3696 return str_replace( '<!--MWTOC-->', $toc, $full );
3697 } else {
3698 return $full;
3699 }
3700 }
3701
3702 /**
3703 * Transform wiki markup when saving a page by doing \r\n -> \n
3704 * conversion, substitting signatures, {{subst:}} templates, etc.
3705 *
3706 * @param string $text the text to transform
3707 * @param Title &$title the Title object for the current article
3708 * @param User &$user the User object describing the current user
3709 * @param ParserOptions $options parsing options
3710 * @param bool $clearState whether to clear the parser state first
3711 * @return string the altered wiki markup
3712 * @public
3713 */
3714 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3715 $this->mOptions = $options;
3716 $this->setTitle( $title );
3717 $this->setOutputType( self::OT_WIKI );
3718
3719 if ( $clearState ) {
3720 $this->clearState();
3721 }
3722
3723 $pairs = array(
3724 "\r\n" => "\n",
3725 );
3726 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3727 $text = $this->pstPass2( $text, $user );
3728 $text = $this->mStripState->unstripBoth( $text );
3729 return $text;
3730 }
3731
3732 /**
3733 * Pre-save transform helper function
3734 * @private
3735 */
3736 function pstPass2( $text, $user ) {
3737 global $wgContLang, $wgLocaltimezone;
3738
3739 /* Note: This is the timestamp saved as hardcoded wikitext to
3740 * the database, we use $wgContLang here in order to give
3741 * everyone the same signature and use the default one rather
3742 * than the one selected in each user's preferences.
3743 *
3744 * (see also bug 12815)
3745 */
3746 $ts = $this->mOptions->getTimestamp();
3747 $tz = wfMsgForContent( 'timezone-utc' );
3748 if ( isset( $wgLocaltimezone ) ) {
3749 $unixts = wfTimestamp( TS_UNIX, $ts );
3750 $oldtz = getenv( 'TZ' );
3751 putenv( 'TZ='.$wgLocaltimezone );
3752 $ts = date( 'YmdHis', $unixts );
3753 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3754 putenv( 'TZ='.$oldtz );
3755 }
3756
3757 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3758
3759 # Variable replacement
3760 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3761 $text = $this->replaceVariables( $text );
3762
3763 # Signatures
3764 $sigText = $this->getUserSig( $user );
3765 $text = strtr( $text, array(
3766 '~~~~~' => $d,
3767 '~~~~' => "$sigText $d",
3768 '~~~' => $sigText
3769 ) );
3770
3771 # Context links: [[|name]] and [[name (context)|]]
3772 #
3773 global $wgLegalTitleChars;
3774 $tc = "[$wgLegalTitleChars]";
3775 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3776
3777 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3778 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3779 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3780 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3781
3782 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3783 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3784 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3785 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3786
3787 $t = $this->mTitle->getText();
3788 $m = array();
3789 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3790 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3791 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3792 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3793 } else {
3794 # if there's no context, don't bother duplicating the title
3795 $text = preg_replace( $p2, '[[\\1]]', $text );
3796 }
3797
3798 # Trim trailing whitespace
3799 $text = rtrim( $text );
3800
3801 return $text;
3802 }
3803
3804 /**
3805 * Fetch the user's signature text, if any, and normalize to
3806 * validated, ready-to-insert wikitext.
3807 *
3808 * @param User $user
3809 * @return string
3810 * @private
3811 */
3812 function getUserSig( &$user ) {
3813 global $wgMaxSigChars;
3814
3815 $username = $user->getName();
3816 $nickname = $user->getOption( 'nickname' );
3817 $nickname = $nickname === '' ? $username : $nickname;
3818
3819 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3820 $nickname = $username;
3821 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3822 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3823 # Sig. might contain markup; validate this
3824 if( $this->validateSig( $nickname ) !== false ) {
3825 # Validated; clean up (if needed) and return it
3826 return $this->cleanSig( $nickname, true );
3827 } else {
3828 # Failed to validate; fall back to the default
3829 $nickname = $username;
3830 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
3831 }
3832 }
3833
3834 // Make sure nickname doesnt get a sig in a sig
3835 $nickname = $this->cleanSigInSig( $nickname );
3836
3837 # If we're still here, make it a link to the user page
3838 $userText = wfEscapeWikiText( $username );
3839 $nickText = wfEscapeWikiText( $nickname );
3840 if ( $user->isAnon() ) {
3841 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3842 } else {
3843 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3844 }
3845 }
3846
3847 /**
3848 * Check that the user's signature contains no bad XML
3849 *
3850 * @param string $text
3851 * @return mixed An expanded string, or false if invalid.
3852 */
3853 function validateSig( $text ) {
3854 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
3855 }
3856
3857 /**
3858 * Clean up signature text
3859 *
3860 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3861 * 2) Substitute all transclusions
3862 *
3863 * @param string $text
3864 * @param $parsing Whether we're cleaning (preferences save) or parsing
3865 * @return string Signature text
3866 */
3867 function cleanSig( $text, $parsing = false ) {
3868 if ( !$parsing ) {
3869 global $wgTitle;
3870 $this->clearState();
3871 $this->setTitle( $wgTitle );
3872 $this->mOptions = new ParserOptions;
3873 $this->setOutputType = self::OT_PREPROCESS;
3874 }
3875
3876 # Option to disable this feature
3877 if ( !$this->mOptions->getCleanSignatures() ) {
3878 return $text;
3879 }
3880
3881 # FIXME: regex doesn't respect extension tags or nowiki
3882 # => Move this logic to braceSubstitution()
3883 $substWord = MagicWord::get( 'subst' );
3884 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3885 $substText = '{{' . $substWord->getSynonym( 0 );
3886
3887 $text = preg_replace( $substRegex, $substText, $text );
3888 $text = $this->cleanSigInSig( $text );
3889 $dom = $this->preprocessToDom( $text );
3890 $frame = $this->getPreprocessor()->newFrame();
3891 $text = $frame->expand( $dom );
3892
3893 if ( !$parsing ) {
3894 $text = $this->mStripState->unstripBoth( $text );
3895 }
3896
3897 return $text;
3898 }
3899
3900 /**
3901 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3902 * @param string $text
3903 * @return string Signature text with /~{3,5}/ removed
3904 */
3905 function cleanSigInSig( $text ) {
3906 $text = preg_replace( '/~{3,5}/', '', $text );
3907 return $text;
3908 }
3909
3910 /**
3911 * Set up some variables which are usually set up in parse()
3912 * so that an external function can call some class members with confidence
3913 * @public
3914 */
3915 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3916 $this->setTitle( $title );
3917 $this->mOptions = $options;
3918 $this->setOutputType( $outputType );
3919 if ( $clearState ) {
3920 $this->clearState();
3921 }
3922 }
3923
3924 /**
3925 * Wrapper for preprocess()
3926 *
3927 * @param string $text the text to preprocess
3928 * @param ParserOptions $options options
3929 * @return string
3930 * @public
3931 */
3932 function transformMsg( $text, $options ) {
3933 global $wgTitle;
3934 static $executing = false;
3935
3936 # Guard against infinite recursion
3937 if ( $executing ) {
3938 return $text;
3939 }
3940 $executing = true;
3941
3942 wfProfileIn(__METHOD__);
3943 $text = $this->preprocess( $text, $wgTitle, $options );
3944
3945 $executing = false;
3946 wfProfileOut(__METHOD__);
3947 return $text;
3948 }
3949
3950 /**
3951 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3952 * The callback should have the following form:
3953 * function myParserHook( $text, $params, &$parser ) { ... }
3954 *
3955 * Transform and return $text. Use $parser for any required context, e.g. use
3956 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3957 *
3958 * @public
3959 *
3960 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3961 * @param mixed $callback The callback function (and object) to use for the tag
3962 *
3963 * @return The old value of the mTagHooks array associated with the hook
3964 */
3965 function setHook( $tag, $callback ) {
3966 $tag = strtolower( $tag );
3967 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3968 $this->mTagHooks[$tag] = $callback;
3969 if( !in_array( $tag, $this->mStripList ) ) {
3970 $this->mStripList[] = $tag;
3971 }
3972
3973 return $oldVal;
3974 }
3975
3976 function setTransparentTagHook( $tag, $callback ) {
3977 $tag = strtolower( $tag );
3978 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3979 $this->mTransparentTagHooks[$tag] = $callback;
3980
3981 return $oldVal;
3982 }
3983
3984 /**
3985 * Remove all tag hooks
3986 */
3987 function clearTagHooks() {
3988 $this->mTagHooks = array();
3989 $this->mStripList = $this->mDefaultStripList;
3990 }
3991
3992 /**
3993 * Create a function, e.g. {{sum:1|2|3}}
3994 * The callback function should have the form:
3995 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3996 *
3997 * Or with SFH_OBJECT_ARGS:
3998 * function myParserFunction( $parser, $frame, $args ) { ... }
3999 *
4000 * The callback may either return the text result of the function, or an array with the text
4001 * in element 0, and a number of flags in the other elements. The names of the flags are
4002 * specified in the keys. Valid flags are:
4003 * found The text returned is valid, stop processing the template. This
4004 * is on by default.
4005 * nowiki Wiki markup in the return value should be escaped
4006 * isHTML The returned text is HTML, armour it against wikitext transformation
4007 *
4008 * @public
4009 *
4010 * @param string $id The magic word ID
4011 * @param mixed $callback The callback function (and object) to use
4012 * @param integer $flags a combination of the following flags:
4013 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4014 *
4015 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4016 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4017 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4018 * the arguments, and to control the way they are expanded.
4019 *
4020 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4021 * arguments, for instance:
4022 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4023 *
4024 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4025 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4026 * working if/when this is changed.
4027 *
4028 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4029 * expansion.
4030 *
4031 * Please read the documentation in includes/parser/Preprocessor.php for more information
4032 * about the methods available in PPFrame and PPNode.
4033 *
4034 * @return The old callback function for this name, if any
4035 */
4036 function setFunctionHook( $id, $callback, $flags = 0 ) {
4037 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4038 $this->mFunctionHooks[$id] = array( $callback, $flags );
4039
4040 # Add to function cache
4041 $mw = MagicWord::get( $id );
4042 if( !$mw )
4043 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4044
4045 $synonyms = $mw->getSynonyms();
4046 $sensitive = intval( $mw->isCaseSensitive() );
4047
4048 foreach ( $synonyms as $syn ) {
4049 # Case
4050 if ( !$sensitive ) {
4051 $syn = strtolower( $syn );
4052 }
4053 # Add leading hash
4054 if ( !( $flags & SFH_NO_HASH ) ) {
4055 $syn = '#' . $syn;
4056 }
4057 # Remove trailing colon
4058 if ( substr( $syn, -1, 1 ) === ':' ) {
4059 $syn = substr( $syn, 0, -1 );
4060 }
4061 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4062 }
4063 return $oldVal;
4064 }
4065
4066 /**
4067 * Get all registered function hook identifiers
4068 *
4069 * @return array
4070 */
4071 function getFunctionHooks() {
4072 return array_keys( $this->mFunctionHooks );
4073 }
4074
4075 /**
4076 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4077 * Placeholders created in Skin::makeLinkObj()
4078 * Returns an array of link CSS classes, indexed by PDBK.
4079 */
4080 function replaceLinkHolders( &$text, $options = 0 ) {
4081 return $this->mLinkHolders->replace( $text );
4082 }
4083
4084 /**
4085 * Replace <!--LINK--> link placeholders with plain text of links
4086 * (not HTML-formatted).
4087 * @param string $text
4088 * @return string
4089 */
4090 function replaceLinkHoldersText( $text ) {
4091 return $this->mLinkHolders->replaceText( $text );
4092 }
4093
4094 /**
4095 * Tag hook handler for 'pre'.
4096 */
4097 function renderPreTag( $text, $attribs ) {
4098 // Backwards-compatibility hack
4099 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4100
4101 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4102 return wfOpenElement( 'pre', $attribs ) .
4103 Xml::escapeTagsOnly( $content ) .
4104 '</pre>';
4105 }
4106
4107 /**
4108 * Renders an image gallery from a text with one line per image.
4109 * text labels may be given by using |-style alternative text. E.g.
4110 * Image:one.jpg|The number "1"
4111 * Image:tree.jpg|A tree
4112 * given as text will return the HTML of a gallery with two images,
4113 * labeled 'The number "1"' and
4114 * 'A tree'.
4115 */
4116 function renderImageGallery( $text, $params ) {
4117 $ig = new ImageGallery();
4118 $ig->setContextTitle( $this->mTitle );
4119 $ig->setShowBytes( false );
4120 $ig->setShowFilename( false );
4121 $ig->setParser( $this );
4122 $ig->setHideBadImages();
4123 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4124 $ig->useSkin( $this->mOptions->getSkin() );
4125 $ig->mRevisionId = $this->mRevisionId;
4126
4127 if( isset( $params['caption'] ) ) {
4128 $caption = $params['caption'];
4129 $caption = htmlspecialchars( $caption );
4130 $caption = $this->replaceInternalLinks( $caption );
4131 $ig->setCaptionHtml( $caption );
4132 }
4133 if( isset( $params['perrow'] ) ) {
4134 $ig->setPerRow( $params['perrow'] );
4135 }
4136 if( isset( $params['widths'] ) ) {
4137 $ig->setWidths( $params['widths'] );
4138 }
4139 if( isset( $params['heights'] ) ) {
4140 $ig->setHeights( $params['heights'] );
4141 }
4142
4143 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4144
4145 $lines = StringUtils::explode( "\n", $text );
4146 foreach ( $lines as $line ) {
4147 # match lines like these:
4148 # Image:someimage.jpg|This is some image
4149 $matches = array();
4150 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4151 # Skip empty lines
4152 if ( count( $matches ) == 0 ) {
4153 continue;
4154 }
4155
4156 if ( strpos( $matches[0], '%' ) !== false )
4157 $matches[1] = urldecode( $matches[1] );
4158 $tp = Title::newFromText( $matches[1]/*, NS_IMAGE*/ );
4159 $nt =& $tp;
4160 if( is_null( $nt ) ) {
4161 # Bogus title. Ignore these so we don't bomb out later.
4162 continue;
4163 }
4164 if ( isset( $matches[3] ) ) {
4165 $label = $matches[3];
4166 } else {
4167 $label = '';
4168 }
4169
4170 $html = $this->recursiveTagParse( trim( $label ) );
4171
4172 $ig->add( $nt, $html );
4173
4174 # Only add real images (bug #5586)
4175 if ( $nt->getNamespace() == NS_IMAGE ) {
4176 $this->mOutput->addImage( $nt->getDBkey() );
4177 }
4178 }
4179 return $ig->toHTML();
4180 }
4181
4182 /** Renders any text in between <poem></poem> tags
4183 * based on http://www.mediawiki.org/wiki/Extension:Poem
4184 */
4185
4186 function renderPoem( $in, $param = array() ) {
4187
4188 /* using newlines in the text will cause the parser to add <p> tags,
4189 * which may not be desired in some cases
4190 */
4191 $nl = array_key_exists( 'compact', $param ) ? '' : "\n";
4192
4193 $replacer = new DoubleReplacer( ' ', '&nbsp;' );
4194 $text = $this->recursiveTagParse( $in );
4195 $text = $this->mStripState->unstripNoWiki( $text );
4196 // Only strip the very first and very last \n (which trim cannot do)
4197 if( substr( $text, 0, 1 ) == "\n" )
4198 $text = substr( $text, 1 );
4199 if( substr( $text, -1 ) == "\n" )
4200 $text = substr( $text, 0, -1 );
4201
4202 $text = str_replace( "\n", "<br />\n", $text );
4203 $text = preg_replace_callback(
4204 "/^( +)/m",
4205 $replacer->cb(),
4206 $text );
4207
4208 // Pass HTML attributes through to the output.
4209 $attribs = Sanitizer::validateTagAttributes( $param, 'div' );
4210
4211 // Wrap output in a <div> with "poem" class.
4212 if( array_key_exists( 'class', $attribs ) ) {
4213 $attribs['class'] = 'poem ' . $attribs['class'];
4214 } else {
4215 $attribs['class'] = 'poem';
4216 }
4217
4218 return Xml::openElement( 'div', $attribs ) . $nl . trim( $text ) . $nl . Xml::closeElement( 'div' );
4219 }
4220
4221 function getImageParams( $handler ) {
4222 if ( $handler ) {
4223 $handlerClass = get_class( $handler );
4224 } else {
4225 $handlerClass = '';
4226 }
4227 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4228 // Initialise static lists
4229 static $internalParamNames = array(
4230 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4231 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4232 'bottom', 'text-bottom' ),
4233 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4234 'upright', 'border', 'link', 'alt' ),
4235 );
4236 static $internalParamMap;
4237 if ( !$internalParamMap ) {
4238 $internalParamMap = array();
4239 foreach ( $internalParamNames as $type => $names ) {
4240 foreach ( $names as $name ) {
4241 $magicName = str_replace( '-', '_', "img_$name" );
4242 $internalParamMap[$magicName] = array( $type, $name );
4243 }
4244 }
4245 }
4246
4247 // Add handler params
4248 $paramMap = $internalParamMap;
4249 if ( $handler ) {
4250 $handlerParamMap = $handler->getParamMap();
4251 foreach ( $handlerParamMap as $magic => $paramName ) {
4252 $paramMap[$magic] = array( 'handler', $paramName );
4253 }
4254 }
4255 $this->mImageParams[$handlerClass] = $paramMap;
4256 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4257 }
4258 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4259 }
4260
4261 /**
4262 * Parse image options text and use it to make an image
4263 * @param Title $title
4264 * @param string $options
4265 * @param LinkHolderArray $holders
4266 */
4267 function makeImage( $title, $options, $holders = false ) {
4268 # Check if the options text is of the form "options|alt text"
4269 # Options are:
4270 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4271 # * left no resizing, just left align. label is used for alt= only
4272 # * right same, but right aligned
4273 # * none same, but not aligned
4274 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4275 # * center center the image
4276 # * framed Keep original image size, no magnify-button.
4277 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4278 # * upright reduce width for upright images, rounded to full __0 px
4279 # * border draw a 1px border around the image
4280 # * alt Text for HTML alt attribute (defaults to empty)
4281 # vertical-align values (no % or length right now):
4282 # * baseline
4283 # * sub
4284 # * super
4285 # * top
4286 # * text-top
4287 # * middle
4288 # * bottom
4289 # * text-bottom
4290
4291 $parts = StringUtils::explode( "|", $options );
4292 $sk = $this->mOptions->getSkin();
4293
4294 # Give extensions a chance to select the file revision for us
4295 $skip = $time = $descQuery = false;
4296 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4297
4298 if ( $skip ) {
4299 return $sk->link( $title );
4300 }
4301
4302 # Get the file
4303 $imagename = $title->getDBkey();
4304 if ( isset( $this->mFileCache[$imagename][$time] ) ) {
4305 $file = $this->mFileCache[$imagename][$time];
4306 } else {
4307 $file = wfFindFile( $title, $time );
4308 if ( !(count( $this->mFileCache ) <= 1000) ) {
4309 $this->mFileCache = array();
4310 }
4311 $this->mFileCache[$imagename][$time] = $file;
4312 }
4313 # Get parameter map
4314 $handler = $file ? $file->getHandler() : false;
4315
4316 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4317
4318 # Process the input parameters
4319 $caption = '';
4320 $params = array( 'frame' => array(), 'handler' => array(),
4321 'horizAlign' => array(), 'vertAlign' => array() );
4322 foreach( $parts as $part ) {
4323 $part = trim( $part );
4324 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4325 $validated = false;
4326 if( isset( $paramMap[$magicName] ) ) {
4327 list( $type, $paramName ) = $paramMap[$magicName];
4328
4329 // Special case; width and height come in one variable together
4330 if( $type === 'handler' && $paramName === 'width' ) {
4331 $m = array();
4332 # (bug 13500) In both cases (width/height and width only),
4333 # permit trailing "px" for backward compatibility.
4334 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4335 $width = intval( $m[1] );
4336 $height = intval( $m[2] );
4337 if ( $handler->validateParam( 'width', $width ) ) {
4338 $params[$type]['width'] = $width;
4339 $validated = true;
4340 }
4341 if ( $handler->validateParam( 'height', $height ) ) {
4342 $params[$type]['height'] = $height;
4343 $validated = true;
4344 }
4345 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4346 $width = intval( $value );
4347 if ( $handler->validateParam( 'width', $width ) ) {
4348 $params[$type]['width'] = $width;
4349 $validated = true;
4350 }
4351 } // else no validation -- bug 13436
4352 } else {
4353 if ( $type === 'handler' ) {
4354 # Validate handler parameter
4355 $validated = $handler->validateParam( $paramName, $value );
4356 } else {
4357 # Validate internal parameters
4358 switch( $paramName ) {
4359 case 'manualthumb':
4360 case 'alt':
4361 // @fixme - possibly check validity here for
4362 // manualthumb? downstream behavior seems odd with
4363 // missing manual thumbs.
4364 $validated = true;
4365 break;
4366 case 'link':
4367 $chars = self::EXT_LINK_URL_CLASS;
4368 $prots = $this->mUrlProtocols;
4369 if ( $value === '' ) {
4370 $paramName = 'no-link';
4371 $value = true;
4372 $validated = true;
4373 } elseif ( preg_match( "/^$prots/", $value ) ) {
4374 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4375 $paramName = 'link-url';
4376 $this->mOutput->addExternalLink( $value );
4377 $validated = true;
4378 }
4379 } else {
4380 $linkTitle = Title::newFromText( $value );
4381 if ( $linkTitle ) {
4382 $paramName = 'link-title';
4383 $value = $linkTitle;
4384 $this->mOutput->addLink( $linkTitle );
4385 $validated = true;
4386 }
4387 }
4388 break;
4389 default:
4390 // Most other things appear to be empty or numeric...
4391 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4392 }
4393 }
4394
4395 if ( $validated ) {
4396 $params[$type][$paramName] = $value;
4397 }
4398 }
4399 }
4400 if ( !$validated ) {
4401 $caption = $part;
4402 }
4403 }
4404
4405 # Process alignment parameters
4406 if ( $params['horizAlign'] ) {
4407 $params['frame']['align'] = key( $params['horizAlign'] );
4408 }
4409 if ( $params['vertAlign'] ) {
4410 $params['frame']['valign'] = key( $params['vertAlign'] );
4411 }
4412
4413 $params['frame']['caption'] = $caption;
4414
4415 # Strip bad stuff out of the title (tooltip). We can't just use
4416 # replaceLinkHoldersText() here, because if this function is called
4417 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4418 if ( $holders ) {
4419 $tooltip = $holders->replaceText( $caption );
4420 } else {
4421 $tooltip = $this->replaceLinkHoldersText( $caption );
4422 }
4423
4424 # make sure there are no placeholders in thumbnail attributes
4425 # that are later expanded to html- so expand them now and
4426 # remove the tags
4427 $tooltip = $this->mStripState->unstripBoth( $tooltip );
4428 $tooltip = Sanitizer::stripAllTags( $tooltip );
4429
4430 $params['frame']['title'] = $tooltip;
4431
4432 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4433 # came to also set the caption, ordinary text after the image -- which
4434 # makes no sense, because that just repeats the text multiple times in
4435 # screen readers. It *also* came to set the title attribute.
4436 #
4437 # Now that we have an alt attribute, we should not set the alt text to
4438 # equal the caption: that's worse than useless, it just repeats the
4439 # text. This is the framed/thumbnail case. If there's no caption, we
4440 # use the unnamed parameter for alt text as well, just for the time be-
4441 # ing, if the unnamed param is set and the alt param is not.
4442 #
4443 # For the future, we need to figure out if we want to tweak this more,
4444 # e.g., introducing a title= parameter for the title; ignoring the un-
4445 # named parameter entirely for images without a caption; adding an ex-
4446 # plicit caption= parameter and preserving the old magic unnamed para-
4447 # meter for BC; ...
4448 if( $caption !== '' && !isset( $params['frame']['alt'] )
4449 && !isset( $params['frame']['framed'] )
4450 && !isset( $params['frame']['thumbnail'] )
4451 && !isset( $params['frame']['manualthumb'] ) ) {
4452 $params['frame']['alt'] = $tooltip;
4453 }
4454
4455 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4456
4457 # Linker does the rest
4458 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4459
4460 # Give the handler a chance to modify the parser object
4461 if ( $handler ) {
4462 $handler->parserTransformHook( $this, $file );
4463 }
4464
4465 return $ret;
4466 }
4467
4468 /**
4469 * Set a flag in the output object indicating that the content is dynamic and
4470 * shouldn't be cached.
4471 */
4472 function disableCache() {
4473 wfDebug( "Parser output marked as uncacheable.\n" );
4474 $this->mOutput->mCacheTime = -1;
4475 }
4476
4477 /**#@+
4478 * Callback from the Sanitizer for expanding items found in HTML attribute
4479 * values, so they can be safely tested and escaped.
4480 * @param string $text
4481 * @param PPFrame $frame
4482 * @return string
4483 * @private
4484 */
4485 function attributeStripCallback( &$text, $frame = false ) {
4486 $text = $this->replaceVariables( $text, $frame );
4487 $text = $this->mStripState->unstripBoth( $text );
4488 return $text;
4489 }
4490
4491 /**#@-*/
4492
4493 /**#@+
4494 * Accessor/mutator
4495 */
4496 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4497 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4498 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4499 /**#@-*/
4500
4501 /**#@+
4502 * Accessor
4503 */
4504 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4505 /**#@-*/
4506
4507
4508 /**
4509 * Break wikitext input into sections, and either pull or replace
4510 * some particular section's text.
4511 *
4512 * External callers should use the getSection and replaceSection methods.
4513 *
4514 * @param string $text Page wikitext
4515 * @param string $section A section identifier string of the form:
4516 * <flag1> - <flag2> - ... - <section number>
4517 *
4518 * Currently the only recognised flag is "T", which means the target section number
4519 * was derived during a template inclusion parse, in other words this is a template
4520 * section edit link. If no flags are given, it was an ordinary section edit link.
4521 * This flag is required to avoid a section numbering mismatch when a section is
4522 * enclosed by <includeonly> (bug 6563).
4523 *
4524 * The section number 0 pulls the text before the first heading; other numbers will
4525 * pull the given section along with its lower-level subsections. If the section is
4526 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4527 *
4528 * @param string $mode One of "get" or "replace"
4529 * @param string $newText Replacement text for section data.
4530 * @return string for "get", the extracted section text.
4531 * for "replace", the whole page with the section replaced.
4532 */
4533 private function extractSections( $text, $section, $mode, $newText='' ) {
4534 global $wgTitle;
4535 $this->clearState();
4536 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4537 $this->mOptions = new ParserOptions;
4538 $this->setOutputType( self::OT_WIKI );
4539 $outText = '';
4540 $frame = $this->getPreprocessor()->newFrame();
4541
4542 // Process section extraction flags
4543 $flags = 0;
4544 $sectionParts = explode( '-', $section );
4545 $sectionIndex = array_pop( $sectionParts );
4546 foreach ( $sectionParts as $part ) {
4547 if ( $part === 'T' ) {
4548 $flags |= self::PTD_FOR_INCLUSION;
4549 }
4550 }
4551 // Preprocess the text
4552 $root = $this->preprocessToDom( $text, $flags );
4553
4554 // <h> nodes indicate section breaks
4555 // They can only occur at the top level, so we can find them by iterating the root's children
4556 $node = $root->getFirstChild();
4557
4558 // Find the target section
4559 if ( $sectionIndex == 0 ) {
4560 // Section zero doesn't nest, level=big
4561 $targetLevel = 1000;
4562 } else {
4563 while ( $node ) {
4564 if ( $node->getName() === 'h' ) {
4565 $bits = $node->splitHeading();
4566 if ( $bits['i'] == $sectionIndex ) {
4567 $targetLevel = $bits['level'];
4568 break;
4569 }
4570 }
4571 if ( $mode === 'replace' ) {
4572 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4573 }
4574 $node = $node->getNextSibling();
4575 }
4576 }
4577
4578 if ( !$node ) {
4579 // Not found
4580 if ( $mode === 'get' ) {
4581 return $newText;
4582 } else {
4583 return $text;
4584 }
4585 }
4586
4587 // Find the end of the section, including nested sections
4588 do {
4589 if ( $node->getName() === 'h' ) {
4590 $bits = $node->splitHeading();
4591 $curLevel = $bits['level'];
4592 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4593 break;
4594 }
4595 }
4596 if ( $mode === 'get' ) {
4597 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4598 }
4599 $node = $node->getNextSibling();
4600 } while ( $node );
4601
4602 // Write out the remainder (in replace mode only)
4603 if ( $mode === 'replace' ) {
4604 // Output the replacement text
4605 // Add two newlines on -- trailing whitespace in $newText is conventionally
4606 // stripped by the editor, so we need both newlines to restore the paragraph gap
4607 $outText .= $newText . "\n\n";
4608 while ( $node ) {
4609 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4610 $node = $node->getNextSibling();
4611 }
4612 }
4613
4614 if ( is_string( $outText ) ) {
4615 // Re-insert stripped tags
4616 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4617 }
4618
4619 return $outText;
4620 }
4621
4622 /**
4623 * This function returns the text of a section, specified by a number ($section).
4624 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4625 * the first section before any such heading (section 0).
4626 *
4627 * If a section contains subsections, these are also returned.
4628 *
4629 * @param string $text text to look in
4630 * @param string $section section identifier
4631 * @param string $deftext default to return if section is not found
4632 * @return string text of the requested section
4633 */
4634 public function getSection( $text, $section, $deftext='' ) {
4635 return $this->extractSections( $text, $section, "get", $deftext );
4636 }
4637
4638 public function replaceSection( $oldtext, $section, $text ) {
4639 return $this->extractSections( $oldtext, $section, "replace", $text );
4640 }
4641
4642 /**
4643 * Get the timestamp associated with the current revision, adjusted for
4644 * the default server-local timestamp
4645 */
4646 function getRevisionTimestamp() {
4647 if ( is_null( $this->mRevisionTimestamp ) ) {
4648 wfProfileIn( __METHOD__ );
4649 global $wgContLang;
4650 $dbr = wfGetDB( DB_SLAVE );
4651 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4652 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4653
4654 // Normalize timestamp to internal MW format for timezone processing.
4655 // This has the added side-effect of replacing a null value with
4656 // the current time, which gives us more sensible behavior for
4657 // previews.
4658 $timestamp = wfTimestamp( TS_MW, $timestamp );
4659
4660 // The cryptic '' timezone parameter tells to use the site-default
4661 // timezone offset instead of the user settings.
4662 //
4663 // Since this value will be saved into the parser cache, served
4664 // to other users, and potentially even used inside links and such,
4665 // it needs to be consistent for all visitors.
4666 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4667
4668 wfProfileOut( __METHOD__ );
4669 }
4670 return $this->mRevisionTimestamp;
4671 }
4672
4673 /**
4674 * Mutator for $mDefaultSort
4675 *
4676 * @param $sort New value
4677 */
4678 public function setDefaultSort( $sort ) {
4679 $this->mDefaultSort = $sort;
4680 }
4681
4682 /**
4683 * Accessor for $mDefaultSort
4684 * Will use the title/prefixed title if none is set
4685 *
4686 * @return string
4687 */
4688 public function getDefaultSort() {
4689 global $wgCategoryPrefixedDefaultSortkey;
4690 if( $this->mDefaultSort !== false ) {
4691 return $this->mDefaultSort;
4692 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4693 !$wgCategoryPrefixedDefaultSortkey) {
4694 return $this->mTitle->getText();
4695 } else {
4696 return $this->mTitle->getPrefixedText();
4697 }
4698 }
4699
4700 /**
4701 * Try to guess the section anchor name based on a wikitext fragment
4702 * presumably extracted from a heading, for example "Header" from
4703 * "== Header ==".
4704 */
4705 public function guessSectionNameFromWikiText( $text ) {
4706 # Strip out wikitext links(they break the anchor)
4707 $text = $this->stripSectionName( $text );
4708 $headline = Sanitizer::decodeCharReferences( $text );
4709 # strip out HTML
4710 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4711 $headline = trim( $headline );
4712 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4713 $replacearray = array(
4714 '%3A' => ':',
4715 '%' => '.'
4716 );
4717 return str_replace(
4718 array_keys( $replacearray ),
4719 array_values( $replacearray ),
4720 $sectionanchor );
4721 }
4722
4723 /**
4724 * Strips a text string of wikitext for use in a section anchor
4725 *
4726 * Accepts a text string and then removes all wikitext from the
4727 * string and leaves only the resultant text (i.e. the result of
4728 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4729 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4730 * to create valid section anchors by mimicing the output of the
4731 * parser when headings are parsed.
4732 *
4733 * @param $text string Text string to be stripped of wikitext
4734 * for use in a Section anchor
4735 * @return Filtered text string
4736 */
4737 public function stripSectionName( $text ) {
4738 # Strip internal link markup
4739 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4740 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4741
4742 # Strip external link markup (FIXME: Not Tolerant to blank link text
4743 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4744 # on how many empty links there are on the page - need to figure that out.
4745 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4746
4747 # Parse wikitext quotes (italics & bold)
4748 $text = $this->doQuotes($text);
4749
4750 # Strip HTML tags
4751 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4752 return $text;
4753 }
4754
4755 function srvus( $text ) {
4756 return $this->testSrvus( $text, $this->mOutputType );
4757 }
4758
4759 /**
4760 * strip/replaceVariables/unstrip for preprocessor regression testing
4761 */
4762 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
4763 $this->clearState();
4764 if ( ! ( $title instanceof Title ) ) {
4765 $title = Title::newFromText( $title );
4766 }
4767 $this->mTitle = $title;
4768 $this->mOptions = $options;
4769 $this->setOutputType( $outputType );
4770 $text = $this->replaceVariables( $text );
4771 $text = $this->mStripState->unstripBoth( $text );
4772 $text = Sanitizer::removeHTMLtags( $text );
4773 return $text;
4774 }
4775
4776 function testPst( $text, $title, $options ) {
4777 global $wgUser;
4778 if ( ! ( $title instanceof Title ) ) {
4779 $title = Title::newFromText( $title );
4780 }
4781 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4782 }
4783
4784 function testPreprocess( $text, $title, $options ) {
4785 if ( ! ( $title instanceof Title ) ) {
4786 $title = Title::newFromText( $title );
4787 }
4788 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
4789 }
4790
4791 function markerSkipCallback( $s, $callback ) {
4792 $i = 0;
4793 $out = '';
4794 while ( $i < strlen( $s ) ) {
4795 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
4796 if ( $markerStart === false ) {
4797 $out .= call_user_func( $callback, substr( $s, $i ) );
4798 break;
4799 } else {
4800 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4801 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
4802 if ( $markerEnd === false ) {
4803 $out .= substr( $s, $markerStart );
4804 break;
4805 } else {
4806 $markerEnd += strlen( self::MARKER_SUFFIX );
4807 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4808 $i = $markerEnd;
4809 }
4810 }
4811 }
4812 return $out;
4813 }
4814 }
4815
4816 /**
4817 * @todo document, briefly.
4818 * @ingroup Parser
4819 */
4820 class StripState {
4821 var $general, $nowiki;
4822
4823 function __construct() {
4824 $this->general = new ReplacementArray;
4825 $this->nowiki = new ReplacementArray;
4826 }
4827
4828 function unstripGeneral( $text ) {
4829 wfProfileIn( __METHOD__ );
4830 do {
4831 $oldText = $text;
4832 $text = $this->general->replace( $text );
4833 } while ( $text !== $oldText );
4834 wfProfileOut( __METHOD__ );
4835 return $text;
4836 }
4837
4838 function unstripNoWiki( $text ) {
4839 wfProfileIn( __METHOD__ );
4840 do {
4841 $oldText = $text;
4842 $text = $this->nowiki->replace( $text );
4843 } while ( $text !== $oldText );
4844 wfProfileOut( __METHOD__ );
4845 return $text;
4846 }
4847
4848 function unstripBoth( $text ) {
4849 wfProfileIn( __METHOD__ );
4850 do {
4851 $oldText = $text;
4852 $text = $this->general->replace( $text );
4853 $text = $this->nowiki->replace( $text );
4854 } while ( $text !== $oldText );
4855 wfProfileOut( __METHOD__ );
4856 return $text;
4857 }
4858 }
4859
4860 /**
4861 * @todo document, briefly.
4862 * @ingroup Parser
4863 */
4864 class OnlyIncludeReplacer {
4865 var $output = '';
4866
4867 function replace( $matches ) {
4868 if ( substr( $matches[1], -1 ) === "\n" ) {
4869 $this->output .= substr( $matches[1], 0, -1 );
4870 } else {
4871 $this->output .= $matches[1];
4872 }
4873 }
4874 }